Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 基于共享字段组合两个查询集_Django_Django Models_Django Queryset - Fatal编程技术网

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
。我需要迭代字典的查询集并为总平均值创建一个新的键吗?啊,你想要(所有这些产品)的平均值吗?