基于共享字段合并两个查询集



我有两个查询集,如下所示:

product_first = Reports.objects.filter(product='product1', type='week', profile__team=team).select_related('profile')
product_second = Reports.objects.filter(product='product2', type='week', profile__team=team).select_related('profile')

它们中的每一个都共享obj.profile.user.username,并且具有其他相似的属性(例如obj.total( - 我试图最终得到一个基于obj.profile.user.username的查询集,但obj.totalproduct_first.total + product_second.total

我正在查询的该表的示例:

user_id  total  total_items  product    type
1        150    15           product1   week
1        180    19           product2   week

我们可以通过对username进行注释和分组来做到这一点:

from django.db.models import F, Sum
qs = Reports.object.filter(
product__in=['product1', 'product2'],
type='week',
profile__team=team
).values('profile_id').annotate(
username=F('profile__user__username')
the_total=Sum('total')
).order_by('profile_id', 'username')

这将导致字典QuerySet,每个字典包含三个键:'profile_id''username''the_total'。因此,对于给定的示例数据,它将如下所示:

<QuerySet [{'profile_id': 1, 'username': 'foo', 'the_total': 330}]>

(给定'foo'是用户对id=1username(。

请注意,the_total将包含所有product1s 和product2s 的totals之和。如果没有product2则它仍将显示product1的总和。如果有多个product1,它将总结这些。

最新更新