Django annotate() multiple times causes wrong answers

前端 未结 3 1321
忘掉有多难
忘掉有多难 2021-01-01 10:50

Django has the great new annotate() function for querysets. However I can\'t get it to work properly for multiple annotations in a single queryset.

For example,

3条回答
  •  [愿得一人]
    2021-01-01 10:53

    I can't guarantee that this will solve your problem, but try appending .order_by() to your call. That is:

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

    The reason for this is that django needs to select all the fields in the ORDER BY clause, which causes otherwise identical results to be selected. By appending .order_by(), you're removing the ORDER BY clause altogether, which prevents this from happening. See the aggregation documentation for more information on this issue.

提交回复
热议问题