2013-07-17 100 views
3

我是Django中的新成員,我正在給自己一個試圖構造此查詢的大頭盔。在Django中使用通過多對多關係進行查詢

  • 我有一個BaseProfileOneToOne字段連接到用戶
  • 我專業的個人資料CustomerProfileOneToOne場連接到BaseProfile
  • CustomerProfile與其他CustomerProfile(因此本身)通過一個RelatedCustomer模型多對多關係
  • RelatedCustomer我指定的from_customerto_customer外鍵



也許你可以更好地理解圖像。

enter image description here

我的問題
給定一個user.id我需要知道的客戶,他連接到(所以通過from_customer的所有其他user.id和to_customer):

所以基本上,首先我需要挖掘從用戶到相關客戶使用反向查找,完成所有設置,然後再回頭瞭解該集合中每個客戶的user.id

EDIT2:

我到目前爲止已經達到了:

# This gives me back a customer profile given a user.id (2) 
cm = CustomerProfile.objects.get(base_profile__user=2) 

# M2M lookup. Given one customer returns all the RelatedCustomer relations 
# that he has as a part of the 'from' M2M 
cm.from_photographer.all() 

鏈接前兩個:給定一個user.id我獲得查詢集 CustomerRelated關係:

rel = CustomerProfile.objects.get(base_profile__user=2).from_photographer.all() 

這給了我b凡在這種情況下,用戶具有user.id = 2TestCustomer4

[<CustomerRelated: from TestCustomer4 to TestCustomer2 >, 
<CustomerRelated: from TestCustomer4 to TestCustomer3 >] 

:ACK類似。

我的問題:

到目前爲止好,但現在有這個設置我怎樣才能得到所有user.id的to_customer
也就是說,如何獲取user.idTestCustomer2TestCustomer3

+0

請檢查是否該爲你工作。 –

+0

@GamesBrainiac感謝您的回答。我已經使用了你的鏈接和建議,但我仍然沒有明白。我編輯了我的問題,添加了與我需要執行的操作相同的SQL。 – Leonardo

+0

看看你是否可以用原始SQL做到這一點。我會嘗試在django ORM中給你解決方案,但即使是我的ORM技能也不是那麼好。 –

回答

0

好吧,像往常一樣,只要你得到答案,它總是比你期望的更容易。

我想這個工作對我來說:

User.objects.filter(base_profile__customer_profile__to_customer__in= 
User.objects.get(id=2).base_profile.customer_profile.from_customer.all()) 

非常感謝@Games智囊團

4

首先,這不是你如何在django中查詢數據庫。其次(因爲你在學習),最好指出你可以運行dbshell來嘗試不同的事情。最後,文檔中描述了這類問題。

我告訴你這一點,因爲作爲一個初學者,我也覺得在整個事情中瀏覽都有點困難。找到東西的最好方法就是使用google,並在最後添加一個django

我知道你的感受,文檔搜索很爛,對吧?嘿,我感覺到你,這就是爲什麼你總是按照我描述的方式去尋找。一旦你掌握了文檔,你會覺得文檔標題頁更直觀一點。

好了,現在到了答案: 要訪問ManyToManyOneToOneForeignKey領域,你需要使用一個__俗稱dunder

所以,這是如何會去做這件事。請注意,還有其他的方法,以及這樣做的潛在的更好的方法:

thing_I_want = RelatedCustomer.objects.get(to_customer__id=2) 

但請注意,如果你想獲得客戶的名單,你會用filter()。下面是一個例子(使用購買的數量爲例):

things_I_want = RelatedCustomer.objects.filter(to_customer__no_of_purchases=16) 

還要注意的是關於過濾器偉大的事情是,你疊在另一個上面一個過濾器。您可以在我下面提供的文檔鏈接中閱讀有關這些功能的更多信息。

這會讓你得到你想要的。現在,您可能會對此有更多疑問,以及它們如何一起工作。不要害怕,請點擊this documentation link查看。

編輯 好像你想做的事可以通過Django的做什麼,但如果你想使用SQL做到這一點,那也是可能的。例如,SomeModel.objects.raw("SQL_HERE")。表格的名稱通常是<app>_<model>

但是,你所要求的也可以在django中使用ORM來完成。但它會很棘手。