【问题标题】:Convert SQL QUERY to Django将 SQL QUERY 转换为 Django
【发布时间】:2017-02-17 23:56:44
【问题描述】:

我在 Postgres 中有下一个查询:

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,但我不知道如何处理那个 Coalesce。我已经这样做了:

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

【问题讨论】:

    标签: sql django postgresql django-queryset


    【解决方案1】:

    尝试将Coalesce 替换为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)
        )
    )
    

    【讨论】:

    • 谢谢,但是不行。它给我的回报比我需要的多。它为我的所有客户返回了所有财务年度
    • 这是一个异常:django.core.exceptions.FieldError: Cannot resolve keyword 'financial_set' into field.
    • @tatulea 你在client = models.ForeignKey(Client, on_delete=models.CASCADE) 中有related_name 吗?
    • 不,型号就在上面
    • @tatulea 用financial 代替financial_set 怎么样?
    猜你喜欢
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2017-08-23
    • 2021-12-17
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多