2016-08-23 89 views
0

我使用distinct() QuerySet在Django中獲取一些數據。
我最初的詢問是Point.objects.order_by('chron', 'pubdate')
字段chron在某些情況下是重複的,因此我將查詢 更改爲Point.objects.order_by('chron', 'pubdate').distinct('chron')以排除重複項。 現在的問題是,所有空字段都被認爲是重複的。查詢排除Django中的重複

爲了準確,chron字段包含整數(其行爲與id類似),在某些情況下,它可以是重複的,在某些情況下,它可以是NULL。

| chron | 
|-------| 
| 1  | I want this 
| 2  | I want this 
| 3  | I want this 
| 3  | 
| NULL | 
| 4  | I want this 
| NULL | 

我要排除所有的chron副本但如果它們是重複的NULL的。 謝謝。

+0

檢查此。 https://stackoverflow.com/questions/30084107/django-query-with-order-by-distinct-and-limit-on-postgresql。然後排除以過濾空結果。 – Windsooon

回答

2

使用兩個單獨的查詢。

  • .distinct("chron").exclude(chron__isnull=True)

  • .filter()僅供chron值,其中chron__isnull=True

雖然這看起來非常低效,我相信(我會很高興得到糾正),即使是任何明智的香草SQL語句(例如低於)將需要多個表掃描到連接的結果集空值和唯一值的。

SELECT * 
FROM (
    SELECT chron 
    FROM Point 
    WHERE chron IS NOT NULL # .exclude() 
    GROUP BY chron # .distinct() 

    UNION ALL 

    SELECT chron 
    FROM Point 
    WHERE chron IS NULL # .include() 
) 
+0

你爲什麼要做'GROUP BY'而不是'SELECT DISTINCT'? –

+0

謝謝,它有一點調整:'chron__isnull'而不是'chron__is_null',我認爲是因爲'chron'是一個'IntegerField'。 – isar

+0

我將用更正的語法更新答案。一定要將問題標記爲已回答。 – Matt