2014-11-02 113 views
0

我奮力想學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 

任何幫助,將不勝感激。

+2

請通過教程。這是一個非常簡單的查詢 - 對於初學者,你可以做一個'.get(id = 5)' – karthikr 2014-11-02 03:24:15

+0

我確實嘗試過這個教程,但它已經躲過了我。我試過 data = Invoice.objects.get(pk = id) 但我只是不明白如何關聯聯繫人字段以獲得聯繫人信息以及(地址等) – Mike 2014-11-02 03:57:52

+0

你會做invoice.contact訪問外鍵。點表示訪問外鍵字段 – karthikr 2014-11-02 04:32:27

回答

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) 
+0

謝謝。這是我需要的提示。現在完美工作。 – Mike 2014-11-02 12:39:20

-2
Contact.invoice_set.filter(id=5) 
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)