django关系查询

时间:2014-11-02 03:16:39

标签: sql django

我正在努力尝试针对两个模型学习Django查询:

class Invoice(models.Model):
    contact = models.ForeignKey(Contact)
    dateCreated =  models.DateTimeField(auto_now_add=True)
    jobName = models.CharField(max_length=30)
    jobAddress = models.CharField(max_length=30, blank=True)

class Contact(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    address = models.CharField(max_length=30)

我正在尝试复制以下查询:

SELECT *
FROM invoice, contact
WHERE invoice.contact_id = contact.id
AND invoice.id = 5

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:2)

您希望以这种方式设置模型:(先联系,然后发票......)

class Contact(models.Model):
  first_name = models.CharField(max_length=30)
  last_name = models.CharField(max_length=30)
  address = models.CharField(max_length=30)

class Invoice(models.Model):
  contact = models.ForeignKey(Contact, related_name="contact_invoice")
  dateCreated =  models.DateTimeField(auto_now_add=True)
  jobName = models.CharField(max_length=30)
  jobAddress = models.CharField(max_length=30, blank=True)

然后这个查询:

contact = Contact.objects.get(id=someid)#just to get first contact object

contact_address = contact.address
contact_firstname = contact.first_name
contact_lastname = contact.last_name
invoice_of_this_contact = contact.contact_invoice.get(id=5)

答案 1 :(得分:1)

所以基本上你想要的是发票的所有信息以及id为5的发票的相关联系人;这样做:

# Fetch the invoice with id = 5
invoice = Invoice.objects.get(id=5)

现在,要获取有关相关联系人的信息,只需“关注”外键:

print(invoice.contact.first_name)
print(invoice.contact.last_name)

答案 2 :(得分:-2)

Contact.invoice_set.filter(id=5)