【发布时间】:2020-04-09 23:20:14
【问题描述】:
型号:
class A(models.Model):
created_on = models.DateTimeField()
class B(models.Model):
a = models.ForeignKey('A', verbose_name='bs')
class C(models.Model):
a = models.ForeignKey('A', verbose_name='cs')
我想用A来统计B和C的个数,然后分组。
这是我的尝试,但结果不正确。
from django.db.models import Count, Q
from django.db.models.functions import Trunc
a_qs = A.objects.filter(Q(created_on__gte=start_date, created_on__lte=end_date))
g = a_qs.objects.annotate(time=Trunc('created_on', 'month')).values('time').order_by('time')
result = g.annotate(a_total=Count('id'), b_total=Count('bs'), c_total=Count('cs'))
虽然这样不会报错,但是结果会不正确。我不想循环查询集。
我有个idea可以满足我的需求,但最后还是需要合并queryset。
a_qs = A.objects.filter(Q(created_on__gte=start_date, created_on__lte=end_date))
a_g = a_qs.annotate(time=Trunc('created_on', 'month')).values('time').order_by('time')
a_result = a_g.annotate(a_total=Count('id'))
b_g = B.objects.filter(a__in=a_qs).annotate(time=Trunc('a__created_on', 'month')).values('time').order_by('time')
b_result = b_g.annotate(b_total=Count('id'))
c_g = ...
c_result = ...
【问题讨论】:
标签: python mysql django django-rest-framework