首页 > 解决方案 > 嵌套子查询区别注释总和

问题描述

所以我想将一个总和注释到一个查询集,它有一个带有来自远程表的变量的小计算规则。

    facturen = Factuur.objects.values('inkoopopdracht').filter(
        inkoopopdracht=OuterRef('pk'),)
    gefactureerd = facturen.annotate(
        gefactureerd=Sum(Case(
            When(
                factuurpost__inkooppost__btw__systematiek=2,
                then=(F(
                    'factuurpost__inkooppost__aantal')*F('factuurpost__inkooppost__eenheidprijs'))),
            default=F(
                'factuurpost__inkooppost__aantal')*F('factuurpost__inkooppost__eenheidprijs')*(
                    1+F('factuurpost__inkooppost__btw__percentage')),
            output_field=DecimalField(),
            )),
        ).values('gefactureerd')
    qs = qs.annotate(
        factuursom=Subquery(gefactureerd.values(
            'gefactureerd'), output_field=DecimalField()),
        )

上述查询的结果是令人满意的。除非有多个“factuurpost”。在这种情况下,总和似乎与 factuurpost 实例相乘。

对此的解决方法是在 Sum 上设置“distinct=True”。然而,由于它只区分值而不区分实例,这引入了一个新问题。类似的值不会被忽略,从而产生错误的总和。

这似乎是其他人也遇到过的问题,例如:Django Count 和 Sum 注释相互干扰

现在,我在那里使用了解决方案和子查询。我试图嵌套子查询无济于事。有没有人看到一个潜在的解决方案让它在所有情况下计算正确的总和?先感谢您!

编辑 模型:

class Factuur(models.Model):

    inkoopopdracht = models.ForeignKey(InkoopOpdracht, models.CASCADE)
    ...


class FactuurPost(models.Model):

    factuur = models.ForeignKey(Factuur, models.CASCADE)
    inkooppost = models.ForeignKey(InkoopPost, on_delete=models.CASCADE)
    aantal = models.IntegerField()
    ...

class InkoopPost(models.Model):

    inkoopopdracht = models.ForeignKey(InkoopOpdracht, models.CASCADE)
    aantal = models.IntegerField()
    eenheidprijs = models.DecimalField(max_digits=10, decimal_places=2)
    ...

标签: djangopostgresqldjango-queryset

解决方案


推荐阅读