Django queryset联合值

时间:2016-10-19 13:45:10

标签: django django-models django-1.10

我想加入用户与没有这些值的用户的相关值之和。

这是我的模型结构的简化版本:

class Answer(models.Model):
    person = models.ForeignKey(Person)
    points = models.PositiveIntegerField(default=100)
    correct = models.BooleanField(default=False)

class Person(models.Model):
    # irrelevant model fields

示例数据集:

Person | Answer.Points
------ | ------
3      | 50
3      | 100
2      | 100
2      | 90

Person 4 has no answers and therefore, points

通过下面的查询,我可以获得每个人的积分总和:

people_with_points = Person.objects.\
        filter(answer__correct=True).\
        annotate(points=Sum('answer__points')).\
        values('pk', 'points')

<QuerySet [{'pk': 2, 'points': 190}, {'pk': 3, 'points': 150}]>

但是,由于某些人可能没有任何相关的Answer条目,因此他们将获得0分,并且通过下面的查询,我使用Coalesce来预测&#34;假的&#34;他们的观点如下:

people_without_points = Person.objects.\
        exclude(pk__in=people_with_points.values_list('pk')).\
        annotate(points=Coalesce(Sum('answer__points'), 0)).\
        values('pk', 'points')

<QuerySet [{'pk': 4, 'points': 0}]>

这两个都按预期工作,但我希望将它们放在同一个查询集中,所以我使用union运算符|来加入它们:

everyone = people_with_points | people_without_points

现在,问题

在此之后,没有积分的人将points值变为None而不是0。

<QuerySet [{'pk': 2, 'points': 190}, {'pk': 3, 'points': 150}, {'pk': 4, 'points': None}]>

任何人都知道为什么会这样?

谢谢!

1 个答案:

答案 0 :(得分:1)

我应该提一下,我可以通过再次注释查询集并将空值合并为0来解决这个问题,如下所示:

everyone.\
    annotate(real_points=Concat(Coalesce(F('points'), 0), Value(''))).\
    values('pk', 'real_points')

<QuerySet [{'pk': 2, 'real_points': 190}, {'pk': 3, 'real_points': 150}, {'pk': 4, 'real_points': 0}]>

但我希望理解为什么工会不能像我在原来的问题中那样工作。

编辑: 我想我明白了。一位朋友指示我使用django-debug-toolbar检查我的SQL查询以进一步调查这种情况,我发现了以下内容:

由于它是两个查询的并集,因此不会考虑第二个查询注释,并且不使用COALESCE到0。通过将其移动到第一个查询,它将传播到第二个查询,我可以实现预期的结果。

基本上,我更改了以下内容:

# Moved the "Coalesce" to the initial query
people_with_points = Person.objects.\
    filter(answer__correct=True).\
    annotate(points=Coalesce(Sum('answer__points'), 0)).\
    values('pk', 'points')

# Second query does not have it anymore
people_without_points = Person.objects.\
    exclude(pk__in=people_with_points.values_list('pk')).\
    values('pk', 'points')

# We will have the values with 0 here!
everyone = people_with_points | people_without_points
相关问题