Django 基于共享字段组合两个查询集
我有两个查询集,如下所示:Django 基于共享字段组合两个查询集,django,django-models,django-queryset,Django,Django Models,Django Queryset,我有两个查询集,如下所示: 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'
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.total
是product\u first.total+product\u secondary.total
我正在查询的表的示例:
user_id total total_items product type
1 150 15 product1 week
1 180 19 product2 week
我们可以在
用户名上进行注释和分组:
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')
这将导致字典的查询集
,每个字典包含三个键:'profile\u id'
,'username'
,和'the\u total'
。因此,对于给定的样本数据,它将如下所示:
<QuerySet [{'profile_id': 1, 'username': 'foo', 'the_total': 330}]>
(给定的'foo'
是id=1的用户的用户名
)
请注意,u总计
将包含所有product1
s和product2
s的total
s之和。如果没有product2
,则它仍将显示product1
s的总和。如果有多个产品1
s,它将对这些产品进行汇总。那么对于每个用户id
,您想要汇总总数吗?如果该用户有多个product1
s和/或product2
s怎么办?对。幸运的是,对于每种类型的产品,该表只有一个条目。那里的数据来自已导入的CSV,该CSV已合计每个产品。我可以在CSV中迭代,将总计与合并,并将产品类型设置为“全部”或其他类型,我想,但出于几个原因,我想避免这样做。这正是我想要的。现在来深入研究文档,因为这看起来很神奇。非常感谢。是否有一种方法可以使用total
和total\u项的聚合值来获得平均值?实际上,在annotate()
中,我有total\u items=Sum('total\u items')
,total=Sum('total')
返回预期值,我想做average=total/total\u items
。我尝试了average=total/total_items
,但得到了一个错误,即没有定义total
或total_items
,尽管我在QuerySet
中得到了这两个项目的正确值。是的,average=Avg('total')
(带有'from django.db.models import Avg')。请注意,最好不要使用与其中一个字段相同的名称,因为这可能会导致不正确的查询。这将给出product_1
和product_2
total
s的平均值(product\u 1\u total+product\u 2\u total/2
,我正在尝试product\u 1\u total+product\u 2\u total/product\u 1\u total\u items+product\u 2\u total\u items
。我需要迭代字典的查询集并为总平均值创建一个新的键吗?啊,你想要(所有这些产品)的平均值吗?