mercredi 15 juin 2016

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

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

Aucun commentaire:

Enregistrer un commentaire