2017-08-16 49 views
0

我的發票型號:獲取所有客戶的發票數量與多個身份ID

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(計數)

回答

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) 
+0

這是個不錯的選擇,但是queryset在我的情況下比orderedDict更有用 –