2012-08-06 64 views
9

這裏是我的數據庫查詢:Django的:使用註釋,計數和非重複上一個QuerySet

results = Attachments.objects.filter(currency='current').annotate(num_attachments=Count('article_id')).order_by("num_attachments").distinct('article_id') 

細分查詢如下(據我所知):

  • 首先過濾器是當前附件這是「當前」。
  • 然後計算具有某個'article_id'的那些附件的數量。
  • 然後用每個附件的附件數量與具有article_id的附件數量進行註釋。
  • 然後根據附件的數量進行排名。
  • 然後,使用distinct來削減列表,以便每個article_id值都有一個Attachment對象。

我在PostgreSQL上運行這個,所以根據Django docs,我可以根據字段運行distinct()。

沒有任何錯誤,當我執行查詢,但是當我嘗試迭代,甚至打印以下錯誤是由Django的調試拋出的結果:

NotImplementedError at /function/ 
annotate() + distinct(fields) not implemented. 

從交互提示更詳細的回溯是:

File "<console>", line 1, in <module> 
    File "/Users/Pat/.virtualenvs/envsp/lib/python2.7/site-packages/django/db/models/query.py", line 118, in _result_iter 
    self._fill_cache() 
    File "/Users/Pat/.virtualenvs/envsp/lib/python2.7/site-packages/django/db/models/query.py", line 875, in _fill_cache 
    self._result_cache.append(self._iter.next()) 
    File "/Users/Pat/.virtualenvs/envsp/lib/python2.7/site-packages/django/db/models/query.py", line 291, in iterator 
    for row in compiler.results_iter(): 
    File "/Users/Pat/.virtualenvs/envsp/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 763, in results_iter 
    for rows in self.execute_sql(MULTI): 
    File "/Users/Pat/.virtualenvs/envsp/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 808, in execute_sql 
    sql, params = self.as_sql() 
    File "/Users/Pat/.virtualenvs/envsp/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 107, in as_sql 
    "annotate() + distinct(fields) not implemented.") 
NotImplementedError: annotate() + distinct(fields) not implemented. 

任何人都知道這裏發生了什麼?

+2

似乎很簡單。 'NotImplementedError'是一個Django異常。代碼提高它,讓你知道你現在不能將'annotate'和'distinct'結合在一起,這意味着它現在不能工作。他們可能會在未來解決任何與它有關的問題,但現在你運氣不好。你總是可以訴諸「生吃」,做任何你想做的事情。 – 2012-08-06 15:48:31

+0

在上面的代碼示例中,您缺少一個點「。」。在order_by和distinct字段之間。 – Mikael 2012-08-06 15:50:35

+0

@Chris關於另一個查詢(除了原始SQL)完成同樣的事情的任何想法? – Pat 2012-08-07 00:29:49

回答

5

解決方法是使用values('distinct_fieldname'),因爲這會使該字段上的最終SQL語句執行GROUP BY(您可以添加多個字段名),它本質上是相同的。

舉例來說,如果你想知道有多少篇對於一個給定'filename'你這樣做存在:

results = Attachments.objects.filter(currency='current').values('filename').annotate(num_attachments=Count('article_id')).order_by("num_attachments")