django - 嵌套子查询区别注释总和
问题描述
所以我想将一个总和注释到一个查询集,它有一个带有来自远程表的变量的小计算规则。
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)
...
解决方案
推荐阅读
- java - 如何解决“任务执行失败:app:mergeDebugJavaResource”
- google-bigquery - 如何计算大于或等于前一个的值
- authentication - JMeter 测试用例通过动态 CRM 登录
- reactjs - 父组件重新渲染时,子组件是否会卸载?
- database - 带有编辑表单的 WordPress 自定义表格示例
- bash - 如何以递归方式从文件名中删除字符串
- python - NoReverseMatch at /account/login/ Reverse for '' 未找到。'' 不是 django 3 中的有效视图函数或模式名称
- regex - 正则表达式:匹配 ([^AZ]*) 但如果找到“foo”则停止
- java - AWS SES 获取 MAIL FROM 域状态的“失败”状态,AWS SDK for Java 2.x
- audio - 连接音频文件并在每个音频剪辑之间暂停