在 Django 聚合中使用 ifnull 默认值

Alf*_*ang 5 django default aggregate annotate models

我有以下模型类:

class Goods(models.Model):
    name = models.CharField(max_length=100)

class InRecord(models.Model):
    goods = models.ForeignKey(Goods, related_name='in_records')
    timestamp = models.DateTimeField()
    quantity = models.IntegerField()

class OutRecord(models.Model):
    goods = models.ForeignKey(Goods, related_name='out_records')
    timestamp = models.DateTimeField()
    quantity = models.IntegerField()
Run Code Online (Sandbox Code Playgroud)

因此,我想获得一个 QuerySet,其中包含所有具有正存储库的商品。

另一种描述它的方式是,我想过滤具有比 OutRecord 摘要更大的 InRecord 数量摘要的 Goods。


我试过的:

首先,我使用annotate将摘要添加到查询集中:

qs = Goods.objects.annotate(
        qty_in=Sum(in_records__quantity), 
        qty_out=Sum(out_records_quantity)
    )
Run Code Online (Sandbox Code Playgroud)

这似乎有效,但有一个问题,当某些商品没有相关的 in_records 或 out_records 时,注释的字段返回 None

问题:那么,在这种情况下,我有什么方法可以设置默认值,就像ifnull(max(inreocrd.quantity), 0)sql 中的* 调用一样?


在此之后,我想在该 QuerySet 上添加一个过滤器:

我试过:

qs = qs.filter(qty_in__gt(F(qty_out)))
Run Code Online (Sandbox Code Playgroud)

但是如果没有货物的记录,它仍然不起作用。

请帮忙。

pdw*_*pdw 9

您可以使用 Django 的Coalesce函数。像这样的东西应该在 Django 1.8 或更高版本中工作:

from django.db.models.functions import Coalesce

qs = Goods.objects.annotate(
        qty_in=Sum(Coalesce(in_records__quantity, 0)),
        qty_out=Sum(Coalesce(out_records__quantity, 0))
    )
Run Code Online (Sandbox Code Playgroud)