如何使用列表理解对计算的模型值进行过滤 [英] How to filter on calculated model values using list comprehension
问题描述
我有一个用于计算总计的模型
I have a model where I calculate totals
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)
到目前为止,我的计算字段正确计算并显示在模板中,没有任何问题
So far so good , my calculate fields calculate correctly and are displayed in template without any problem
由于我无法直接按属性过滤,因此建议使用python列表理解力
Since I can not filter directly by the property As suggested i am using python list comprehension
所以这是我写的,确实给了我输出,没有错误。
So this is what I wrote that does give me output and no errors .
po_list = [n for n in Material.objects.all()
if ((F('total_inventory') + F('total_po') - F('total_so')) < F('min_quantity'))]
但是当前列表理解不能正确过滤
我得到的输出应该被过滤掉。我在做什么错?
However Current list comprehension doesn't filter correctly I am getting output that should be filtered out. What i am doing wrong?
它没有过滤任何东西,只是返回了列表而已
It is not filtering anything it is just returning the list a it is
推荐答案
我怀疑您可以在模型类方法上调用 F
。相反,您可以直接从列表理解中的对象调用方法:
I doubt you can call F
on model class methods. You can instead call the methods directly from the objects in the list comprehension:
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]
这篇关于如何使用列表理解对计算的模型值进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!