2014-11-02 3 views
0
나는 두 가지 모델에 대해 장고 쿼리를 배우려고 고군분투

:장고 관계 쿼리

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

+0

튜토리얼을 시도했지만 시도가 없습니다. 내가 시도했습니다 데이터 = Invoice.objects.get (pk = id) 하지만 난 연락처 정보뿐만 아니라 연락처 (주소 등)를 얻기 위해 연락처 필드를 연결하는 방법을 이해하지 – Mike

+0

당신은 액세스 할 수 invoice.contact 할 것입니다 외래 키. 점은 외래 키 필드에 액세스하는 것을 의미합니다. – karthikr

답변

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

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