Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query with simple arithmetic among model fields and comparison with field from another model

(All code below is a simplified representation of the actual code).

If I have the following Django models: -

class Material(models.Model):
    name = models.CharField(max_length=110)

class OrderDetail(models.Model):
    material = models.ForeignKey(Material)
    order_quantity = models.IntegerField()
    quantity_delivered = models.IntegerField(null=True, blank=True)
    is_open = models.BooleanField()
    is_active = models.BooleanField()

class MaterialRequirement(models.Model):
    material = models.ForeignKey(Material)
    quantity = models.IntegerField()

I have with me an instance of the MaterialRequirement model, let's call it material_requirement. I am trying to retrieve OrderDetail objects which satisfy the following criteria:-

1. material = material_requirement.material

2. is_open = True

3. is_active = True

4. order_quantity > quantity_delivered

5. material_requirement.quantity <= order_quantity - quantity_delivered

My question is how do I incorporate the 5th selection criteria in my ORM query below.

order_details = OrderDetail.objects.select_related('material').filter(material=material_requirement.material,
                                                                    is_open=True,
                                                                    is_active=True,
                                                                    order_quantity__gt=F('quantity_delivered'))
like image 503
chefsmart Avatar asked Nov 04 '22 01:11

chefsmart


1 Answers

order_details = (OrderDetail.objects.select_related('material')
                 .filter(material=material_requirement.material,
                         is_open=True,
                         is_active=True,
                         order_quantity__gt=F('quantity_delivered'),
                         quantity_delivered__gte=F('order_quantity') - material_requirement.quantity,
                         )
)
like image 52
Davide R. Avatar answered Nov 15 '22 07:11

Davide R.