Reputation: 944
I have a model:
class SupplierOffer(models.Model):
name = models.CharField(max_length=255, blank=True)
code = models.CharField(max_length=255, blank=True)
brand = models.CharField(max_length=255, blank=True)
And from the outer API I got a list of codebrands:
api_list = [CodeBrand(code=u'N00105004004', brand=u'NOVONOL'), CodeBrand(code=u'N00105004004', brand=u'Preston')]
I want to filter all my supplier offers that match API list items, like this:
result = []
for item in api_list:
result.extend(list(SupplierOffer.objects.filter(code=item.code, brand=item.brand)))
It is not the best solution, because it makes 1 db query per item in api_list.
How can I filter offers in 1 db query?
Upvotes: 0
Views: 1494
Reputation: 5669
You can use Q
queries (more info):
from django.db.models import Q
query = Q()
for item in api_list:
query |= (Q(code=item.code) & Q(brand=item.brand))
SupplierOffer.objects.filter(query)
You will have a single DB request.
Upvotes: 4