这是我的数据库查询:
results = Attachments.objects.filter(currency='current').annotate(num_attachments=Count('article_id')).order_by("num_attachments").distinct('article_id')
查询细分如下(据我所知):
我在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.
任何人都知道这里发生了什么?
答案 0 :(得分:6)
解决方法是使用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")
答案 1 :(得分:0)
我找到了另一种方法,如何克服这个问题-通过使用子查询:
distinct_articles = Attachments.objects.distinct('article_id')
results = Attachments.objects.filter(currency='current').annotate(num_attachments=Count('article_id')).order_by("num_attachments").filter(id__in=distinct_articles)
在Django中,它实际上被评估为一个数据库查询。