[Django]-Django: Filter objects by multiple key,value pairs of one foreign key model

4👍

If I understand you correctly you are looking to OR some query filters, by default Django ANDs all filters together. To introduce ORing you should use Q objects. In your example you would need a combination of ANDing (&) and ORing (|):

from django.db.models import Q

queryset = Car.objects.filter(
    (Q(parameters__name='color') & Q(parameters__value='blue')) | 
    (Q(parameters__name='tire') & Q(parameters__value='Goodyear')) |
    (Q(parameters__name='seat') & Q(parameters__value='leather'))
)

Note the reverse lookup from Car to Parameter.

This should equate to get me all Cars that have parameters: name=color AND value=blue OR parameters: name=tire AND value=Goodyear OR parameters: name=seat AND value=leather.

3👍

Use the Q option.

from django.db.models import Q

query = Q()
query &= (Q(name='color') & Q(value='blue'))
query &= (Q(name='tire') & Q(value="Goodyear"))
query &= (Q(name="seat") & Q(value="leather"))

# List : Force the db call to one call
result = list(Parameters.objects.filter(query))
for c in result:
   c.car

Should works.

Leave a comment