sql - Django annotate() 多次导致错误答案

标签 sql django django-queryset

Django 为查询集提供了很棒的新 annotate() 函数。但是,我无法让它在单个查询集中的多个注释正常工作。

例如,

tour_list = Tour.objects.all().annotate( Count('tourcomment') ).annotate( Count('history') )

一个游览可以包含多个游览评论和历史条目。我试图了解这次旅行有多少评论和历史条目。结果

history__count and tourcomment__count

值将不正确。如果只有一个 annotate() 调用,则该值将是正确的。

两个LEFT OUTER JOIN似乎产生了某种乘法效应。例如,如果某个游览有 3 条历史记录和 3 条评论,则两者的计数值均为 9。 12 条历史记录 + 1 条评论 = 12 个值。 1 条历史记录 + 0 条评论 = 1 条历史记录,0 条评论(这一条恰好返回了正确的值)。

生成的 SQL 调用是:

SELECT `testapp_tour`.`id`, `testapp_tour`.`operator_id`, `testapp_tour`.`name`, `testapp_tour`.`region_id`, `testapp_tour`.`description`, `testapp_tour`.`net_price`, `testapp_tour`.`sales_price`, `testapp_tour`.`enabled`, `testapp_tour`.`num_views`, `testapp_tour`.`create_date`, `testapp_tour`.`modify_date`, `testapp_tour`.`image1`, `testapp_tour`.`image2`, `testapp_tour`.`image3`, `testapp_tour`.`image4`, `testapp_tour`.`notes`, `testapp_tour`.`pickup_time`, `testapp_tour`.`dropoff_time`, COUNT(`testapp_tourcomment`.`id`) AS `tourcomment__count`, COUNT(`testapp_history`.`id`) AS `history__count` 
FROM `testapp_tour` LEFT OUTER JOIN `testapp_tourcomment` ON (`testapp_tour`.`id` = `testapp_tourcomment`.`tour_id`) LEFT OUTER JOIN `testapp_history` ON (`testapp_tour`.`id` = `testapp_history`.`tour_id`)
GROUP BY `testapp_tour`.`id`
ORDER BY `testapp_tour`.`name` ASC

我尝试将两个包含对 annotate () 的单个调用的查询集的结果组合起来,但它无法正常工作...您不能真正保证顺序相同。它看起来过于复杂和困惑,所以我一直在寻找更好的东西......

tour_list = Tour.objects.all().filter(operator__user__exact = request.user ).filter(enabled__exact = True).annotate( Count('tourcomment') )
tour_list_historycount = Tour.objects.all().filter( enabled__exact = True ).annotate( Count('history') )
for i,o in enumerate(tour_list):
    o.history__count = tour_list_historycount[i].history__count

感谢您的帮助。 Stackoverflow 过去拯救了我很多已经得到解答的问题,但我还无法找到这个问题的答案。

最佳答案

感谢您的评论。这不太有效,但它引导我走向正确的方向。我终于能够通过向两个 Count() 调用添加不同来解决这个问题:

Count('tourcomment', distinct=True)

关于sql - Django annotate() 多次导致错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1265190/

相关文章:

sql - Django prefetch_related 与限制

django - 序列化错误重建 Elasticsearch Django 应用程序

python - Django QuerySet 差异方法不起作用

mysql - 如何将此 MySQL 查询转换为 Django 查询?

SQL 服务器 2005 : T-SQL INSERT INTO and OUTPUT timestamp to a variable

c# - 在 LINQ 语句中调用标量函数(无需 EDMX)

sql - 使用 LIKE 'string' vs = 'string' 对 Oracle 的性能有何影响?

python - 无法 pickle : attribute lookup builtin. 功能失败

sql - 格式化 IT 代码以匹配 Power Query/Power BI

python - Django 缓存查询(我不想这样)