我有以下数据模型
客户
有很多地址
有很多信用卡
鉴于信用卡记录,我希望能够找到我可以对其应用的所有地址。
基本上我希望能够编写像这样的查询...
SELECT address.line1, address.line2, address.city,
address.state, address.zip FROM
addresses, creditcards
WHERE
addresses.custid = creditcards.custid and
creditcard.number = 'Thenumber#'
我是Django的新手,我只能想到编写这样的代码,我怀疑它会引发100多个查询。
for acard in creditcard.objects.filter(cardno = 'thenumber#'):
for anaddress in Address.objects.filter(customer = acard.customer):
print anaddress.list_values()
我应该采用不同的设计吗?我想不到在这里使用ManyToMany,因为它在技术上并不是很多?我认为这是错的吗?
这是我想到的模型......
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.,
答案 0 :(得分:3)
您应始终从要实际查询的模型开始。在这种情况下,您需要地址,因此您应该从那里开始。
addresses = Address.objects.filter(customer__creditcard__number = 'thenumber#')