小编tba*_*bak的帖子

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

Django为查询集提供了很好的新annotate()函数.但是,我无法让它在单个查询集中正确处理多个注释.

例如,

tour_list = Tour.objects.all().annotate( Count('tourcomment') ).annotate( Count('history') )
Run Code Online (Sandbox Code Playgroud)

游览可以包含多个tourcomment和历史记录条目.我想知道这次巡演有多少评论和历史条目.所结果的

history__count and tourcomment__count
Run Code Online (Sandbox Code Playgroud)

值不正确.如果只有一个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
Run Code Online (Sandbox Code Playgroud)

我尝试将两个查询集的结果组合在一起,这两个查询集包含对annotate()的单个调用,但是它无法正常工作......您无法保证订单将是相同的.它似乎过于复杂和凌乱,所以我一直在寻找更好的东西......

tour_list = Tour.objects.all().filter(operator__user__exact = request.user …
Run Code Online (Sandbox Code Playgroud)

sql django django-queryset

23
推荐指数
2
解决办法
5017
查看次数

标签 统计

django ×1

django-queryset ×1

sql ×1