如何使用列表理解过滤计算的模型值

2024-04-24 06:42:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个计算总数的模型

class Material(models.Model):
    version = IntegerVersionField( )
    code = models.CharField(max_length=30)
    name = models.CharField(max_length=30)
    slug = models.SlugField(max_length=80, blank=True)
    description = models.TextField(null=True, blank=True)
    min_quantity = models.DecimalField(max_digits=19, decimal_places=10)

    def _get_totalinventory(self):
        from inventory.models import Inventory
        return Inventory.objects.filter(warehouse_Bin__material_UOM__UOM__material=self.id, is_active = True).aggregate(Sum('quantity'))

    total_inventory = property(_get_totalinventory)

    def _get_totalpo(self):
        from purchase.models import POmaterial     
        return POmaterial.objects.filter(material=self.id, is_active = True).aggregate(Sum('quantity'))  

    total_po = property(_get_totalpo)


    def _get_totalso(self):
        from sales.models import SOproduct
        return SOproduct.objects.filter(product__material=self.id ,  is_active=True ).aggregate(Sum('quantity'))  

    total_so = property(_get_totalso)

到目前为止,我的计算字段计算正确,显示在模板中没有任何问题

因为我不能像建议的那样直接按属性过滤,所以我使用python列表理解

所以这是我写的,它确实给了我输出,没有错误。在

^{pr2}$

但是当前的列表理解不能正确过滤 我得到的输出应该被过滤掉。我做错什么了?在

它没有过滤任何东西,只是返回一个列表


Tags: fromimportselfidtruegetreturnobjects
1条回答
网友
1楼 · 发布于 2024-04-24 06:42:16

我怀疑您能否对模型类方法调用F。您可以直接从列表理解中的对象调用方法:

po_list = [n for n in Material.objects.all() if (n.total_inventory['quantity__sum'] 
                                                 + n.total_po['quantity__sum'] 
                                                 - n.total_so['quantity__sum']) 
                                                 < n.min_quantity]

相关问题 更多 >