获取具有多个状态ID的所有客户发票的计数

时间:2017-08-16 12:39:07

标签: python django django-views

我的发票型号:

class Invoice(models.Model):
    client = models.ForeignKey(Clients)
    invoice_number = models.CharField(max_length=100)
    invoice_status = models.ForeignKey(Status, on_delete=models.CASCADE,null=True)

状态模型:

class Status(models.Model):
    invoice_status = models.CharField(max_length=50)

客户端模型:

class Clients(models.Model):
    name = models.CharField(max_length=50)
    address = models.TextField(null=True, blank=True)
    contact_person = models.CharField(max_length=50, null=True, blank=True)

状态为

1.Draft 2.Sent 3.Paid

我尝试了多种方法,但都失败了

invoices = Invoice.objects.values("client").aggregate(Paid=Sum(Case(When(invoice_status__id=1, then=1),output_field=IntegerField())))

我想让所有客户的发票状态统计

预期结果

client_id:1,草稿:4(计数),已发送:5(计数),已付款:0(计数)

1 个答案:

答案 0 :(得分:0)

from collections import OrderedDict
from pprint import pprint
from django.db.models import Count

data = Invoice.objects.prefetch_related('invoice_status') \
    .values('client', 'invoice_status') \
    .annotate(count=Count('id')) \
    .order_by('client') \
    .values_list('client', 'invoice_status__invoice_status', 'count')
user_statuses = OrderedDict()
for client, status, count in data:
    statuses = user_statuses.get(client) or {}
    statuses[status] = count
    user_statuses[client] = statuses
pprint(user_statuses)