从两个不同的模块添加两个字段

我正在制作一个库存管理应用,我想在其中添加模块Enable Multiple Windows中的类字段quantity(值)和quantity_prod字段。此操作的结果应填充类ProductionArticle中的另一个字段quantity_in_stock

我已经尝试过使用F表达式进行注释,并使用article_set进行覆盖保存方法,但是我没有找到一个好的结果,我想知道是否存在不使用复杂方法而直接进行字段之间的数学运算的方法

Article
doitsc 回答:从两个不同的模块添加两个字段

我认为F在这里不合适。因为Article对象可以有多个ProductionArticle。而是使用Sum

from django.db.models import Sum

articles = Article.objects.annotate(prod_quantity=Sum('productarticle__quantity_prod')).annotate(quantity_in_stock=F('prod_quantity')+F('quantity'))

for a in articles:
   print(a.quantity_in_stock)

上述解决方案的替代方法是使用属性方法。但是不建议这样做,因为它会增加数据库命中率:

from django.db.models import Sum
from django.db.models.functions import Coalesce

class Article(models.Model):
    ...
    @property
    def quantity_in_stock(self):
        return self.productionarticle_set.all().aggregate(qsum=Coalesce(Sum('quantity_prod'),0))['qsum'] + self.quantity
本文链接:https://www.f2er.com/3161289.html

大家都在问