2016-10-09 105 views
1

我有一個查詢中Postgres的:轉換SQL查詢的Django

SELECT a.id, a.name, a.code, 
(SELECT coalesce((SELECT MAX(value) FROM financials WHERE client_key=a.id AND year=2016), 0) AS ca_vlr_n) 
FROM clients a 

我想它翻譯成Django的,但我不知道如何處理與合併。我已經這樣做了:

queryset = Client.objects.values('name', 'code').annotate(ca_vlr_n=Coalesce(Max('financial__value'), V(0))) 

但我不知道如何把年的條件。

我的模式是:

class Client(models.Model): 
    name    = models.CharField(help_text="Client's Name", max_length=128, unique=True) 
    code    = models.CharField(help_text="Client's CUI", max_length=50) 

class Financial(models.Model): 
    year    = models.PositiveSmallIntegerField() 
    client    = models.ForeignKey(Client, on_delete=models.CASCADE) 
    value    = models.BigIntegerField() 

回答

0

嘗試用Case

queryset = Client.objects.filter(financial__year=2016,).values('name', 'code').annotate(
    ca_vlr_n=Case(
     When(financial__year=2016, then=Max('financial__value')), 
     output_field=BigIntegerField(), default=V(0) 
    ) 
) 
+0

由於更換Coalesce,但也不行。它比我需要的還多。它將所有客戶的所有財務年數返還給我 – tatulea

+0

@tatulea嘗試添加過濾器。查看更新後的答案 –

+0

這是一個例外:django.core.exceptions.FieldError:無法將關鍵字'financial_set'解析爲字段。 – tatulea