我有一个非常简单的查询,没有按预期行事。
# Retrieve news
news = News.objects.filter(available=True)
if area:
news = news.annotate(Count('areas')).filter(Q(areas__count=0)
|Q(areas=area))
我希望收到没有受影响区域或指定区域的新闻。但我没有得到它们。
当我打印查询时,我得到:
SELECT "chimere_news"."id", "chimere_news"."title",
"chimere_news"."available","chimere_news"."date", "chimere_news"."content",
COUNT("chimere_news_areas"."area_id") AS "areas__count"
FROM "chimere_news"
LEFT OUTER JOIN "chimere_news_areas" ON ("chimere_news"."id" = "chimere_news_areas"."news_id")
LEFT OUTER JOIN "chimere_news_areas" T4 ON ("chimere_news"."id" = T4."news_id")
WHERE ("chimere_news"."available" = True AND (T4."area_id" = 1 ))
GROUP BY "chimere_news"."id", "chimere_news"."title", "chimere_news"."available",
"chimere_news"."date", "chimere_news"."content"
HAVING COUNT("chimere_news_areas"."area_id") = 0
我做错了什么还是Django错误?
答案 0 :(得分:1)
如果您只需将计数与零进行比较,请尝试使用isnull
代替。
if area:
news = news.filter(Q(areas__isnull=True)|Q(areas=area))