django使用filter合并两个查询集或两个注释

时间:2015-02-16 03:00:22

标签: django django-models

我得到了这张桌子:

访问:

member | room | status
'john' | 1    | 1 (successful)
'paul' | 1    | 2 (cancelled)
'john' | 1    | 1 (successful)
'john' | 1    | 2 (cancelled)

我希望得到这个:

访问:

member | successful | cancelled
'john' | 2          | 1
'paul' | 0          | 1

我尝试使用带过滤器的两个注释,但当然,我知道我错了......

obj_visits = obj_visits.annotate(successful=Count('status')).filter(status=1)
obj_visits = obj_visits.annotate(cancelled=Count('status')).filter(status=2)

然后我将这些注释分开并将这些结果合并到一个

obj_visits_approved = Visit.objects.values('member').annotate(successful=Count('status')).filter(status=1)
obj_visits_cancelled = Visit.objects.values('member').annotate(cancelled=Count('status')).filter(status=2)

我得到两个结果:

member | successful
'john' | 2
'paul' | 0

member | cancelled
'john' | 1
'paul' | 1

如果我将这些结果链接起来,我会得到4行...我不能使用obj_visits= obj_visits_approved | obj_visits_cancelled,因为它表示类在每种情况下必须包含相同的值...

1 个答案:

答案 0 :(得分:1)

您应该只需使用memberstatus using a values and annotate query进行分组,就可以这样做:

obj_visits = Visit.objects.values('member','status').annotate(number=Count('status'))