我在哪裏可以找到關於建立這樣的查詢一些信息:使用Django ORM選擇內選擇使用Django ORM
select
SomeField1,
(select count(distinct SomeField2) from SomeTable where SomeCondition) as SomeField3
from
SomeTable2
where
SomeCondition2
?它可能在Django文檔的某處,但我找不到它。
我在哪裏可以找到關於建立這樣的查詢一些信息:使用Django ORM選擇內選擇使用Django ORM
select
SomeField1,
(select count(distinct SomeField2) from SomeTable where SomeCondition) as SomeField3
from
SomeTable2
where
SomeCondition2
?它可能在Django文檔的某處,但我找不到它。
你的兩張桌子有什麼關係?
我猜你需要的數量,有一個代碼片段,而不檢查,
SomeModel2.objects.annotate(new_field=Count('SomeField2',
distinct=True)).filter(condition=condition,
another_condition=condition2).values('new_field', 'Somefield1')
詳情請參閱https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate和How to sort by annotated Count() in a related model in Django。
Django的ORM旨在以每個模型爲基礎及其關係數據(即ForeignKey,ManyToManyRelationship ...)執行查詢。你的例子顯示你需要兩個不相關模型同時得到兩個結果。據我所知,有沒有辦法從單獨做
count = SomeTable.objects.filter(SomeCondition).distinct(SomeField2).count()
somefield1 = SomeTable2.objects.filter(SomeCondition2)
做它拆開但是有可以實現它,如果你真的需要做一些方法,但我不會建議他們:
因爲你的問題是專門這裏你可以找到這些信息,看看Aggregation | Django docs - 它應該幫助你實現一些你想在這裏什麼(具體而言,計數)。
然而,將不相關的表格查詢在一起並不是一件常見的事情。您最好單獨進行查詢並手動將返回的數據關聯在一起,因爲無論如何您的數據庫都會分割該查詢。
在你的情況,我建議你make raw SQL queries您的數據庫,如果你必須運行該查詢,