group by,如果Django中没有值则返回0


def get_queryset(self):
date = datetime.date.today()
current_year = date.today().year
queryset = Subscription.objects.filter(created__year=current_year)
.exclude(user__is_staff=True).values(
month=TruncMonth('created')
).annotate(
total_members=Count('created')
).order_by('month')
return queryset

这是我的group by函数,如果没有特定月份的值,我怎么能得到0

{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"total_members": 9,
"month": "2021-02-01T00:00:00Z"
},
{
"total_members": 3,
"month": "2021-03-01T00:00:00Z"
}
]
}

这是我现在得到的输出,因为一月份没有值,所以没有输出,我想要的是一月份的零

可能您可以使用Coalesce,例如:

from django.db.models import Value as V
from django.db.models.functions import Coalesce

def get_queryset(self):
date = datetime.date.today()
current_year = date.today().year
queryset = Subscription.objects.filter(created__year=current_year)
.exclude(user__is_staff=True).values(
month=TruncMonth('created')
).annotate(
total_members=Coalesec(Count('created'), V(0))
).order_by('month')
return queryset

最新更新