如果一个值大于另一个值,则过滤查询集

Ily*_*bik 3 django

我试图基于两个字段之间的关系来筛选我的查询集。

但是总是会得到我的字段未定义的错误。

我的模型有几个计算列,我只想获取字段A的值大于字段B的记录。

这是我的模特

class Material(models.Model):
    version = IntegerVersionField( )
    code = models.CharField(max_length=30)
    name = models.CharField(max_length=30)
    min_quantity = models.DecimalField(max_digits=19, decimal_places=10)
    max_quantity = models.DecimalField(max_digits=19, decimal_places=10)
    is_active = models.BooleanField(default=True)
    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'))


    totalinventory = 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'))  

    totalpo = 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'))  

    totalso = property(_get_totalpo)


    @property
    def _get_total(self):
        return (totalinventory + totalpo - totalso) 

    total = property(_get_total)
Run Code Online (Sandbox Code Playgroud)

这是我认为要获取条件查询集的行

 po_list = MaterialFilter(request.GET, queryset=Material.objects.filter( total__lte =  min_quantity  ))
Run Code Online (Sandbox Code Playgroud)

但是我得到的错误是未定义min_quantity

可能是什么问题呢 ?


编辑:

我的问题解决了,谢谢@Moses Koledoye,但是在同一代码中,我现在有不同的问题

无法将关键字“总计”解析为字段。选择包括:上午,作者,author_id,BOM,Bomversion,代码,Creation_time,描述,ID,库存,is_active,is_production,itemgroup,itemgroup_id,关键字,materialuom,max_quantity,min_quantity,名称,物料,生产,产品,弹头,trigger_quantity,uom,updated_by,updated_by_id,valid_from,valid_to,版本,Warehousebin

基本上,它不会显示模型中包含的任何计算字段。

Mos*_*oye 8

Django无法编写以值未知的字段为条件的查询。您需要为此使用一个F表达式:

from django.db.models import F

queryset = Material.objects.filter(total__lte = F('min_quantity'))
Run Code Online (Sandbox Code Playgroud)

而您FilterSet成为:

po_list = MaterialFilter(request.GET, queryset = Material.objects.filter(total__lte=F('min_quantity')))
Run Code Online (Sandbox Code Playgroud)

文档

一个F()对象表示一个模型字段或注释的列的值。它使引用模型字段值并使用它们执行数据库操作成为可能,而无需实际将它们从数据库中拉出到Python内存中