I want to make a query where i can apply lookups only when some conditions satisfy. e.g
A customer can pick only that food from stall for which he paid for
class Customer(models.Model):
food_type = models.CharField()
fruit_id = models.ForeignKey(Fruit, null=True)
vegetable_id = models.ForeignKey(Vegetable, null=True)
is_paid = models.BooleanField()
class Food(models.Model):
fruit_id = models.ForeignKey(Fruit, null=True)
vegetable_id = models.ForeignKey(Vegetable, null=True)
So i need to do something like:
q = Food.objects.all()
if Customer.objects.filter(id=(id of customer), food_type='fruit', is_paid=True).exists():
q = q.filter(fruit_id__in=Customer.objects.filter(id=(id of customer), food_type='fruit', is_paid=True).values_list('fruit_id', flat=True))
if Customer.objects.filter(id=(id of customer), food_type='vegetable', is_paid=True).exists():
q = q.filter(vegetable_id__in=Customer.objects.filter(id=(id of customer), food_type='vegetable', is_paid=True).values_list('vegetable_id', flat=True))
How can i optimize this as this is a small example, in my case there are many more conditions. I want to reduce the number of times it is hitting the database. Also is there any way i can use conditional expressions here? e.g When()
Any help will be appreciated.