简体   繁体   English

如何在Django外键关系中进行这种查询?

[英]How do I make this kind of Query in Django foreign key relationships?

I have the following data model 我有以下数据模型

Customers 顾客

Have many Addresses 有很多地址
Have many Credit cards 有很多信用卡

Given a credit card record, I want to be able find out all the addresses that I can apply against it. 给定一张信用卡记录,我希望能够找到我可以针对该记录申请​​的所有地址。

Basically I want to be able to write a query like this... 基本上我希望能够编写这样的查询...

SELECT address.line1, address.line2, address.city, 
address.state, address.zip FROM 
addresses, creditcards 
WHERE
addresses.custid = creditcards.custid and 
creditcard.number = 'Thenumber#'

I am fairly new to Django and I can only think of writing the code like this which I suspect wil fire 100s of queries. 我对Django相当陌生,我只能想到编写这样的代码,我怀疑它会引发100多个查询。

for acard in creditcard.objects.filter(cardno = 'thenumber#'):
    for anaddress in Address.objects.filter(customer = acard.customer):
        print anaddress.list_values()  

Is there a different design that I should adopt? 我应该采用其他设计吗? I cannot think of using ManyToMany here as it is technically not many to many? 我想不起来在这里使用ManyToMany,因为从技术上讲它不是很多对很多? am I thinking this wrong? 我在想这个错吗?

here is the model I had in mind... 这是我想到的模型...

class Customer(models.Model):
    pass

class creditcard(models.Model):
    customer = models.ForeignKey(Customer)

class addresss(models.Model):
    customer = models.ForeignKey(Customer)
    line1 = models.CharField()
    # etc., etc., 

You should always start from the model you want to actually query. 您应该始终从要实际查询的模型开始。 In this case, you want addresses, so you should start from there. 在这种情况下,您需要地址,因此您应该从那里开始。

addresses = Address.objects.filter(customer__creditcard__number = 'thenumber#')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM