I have a model ModelNameHere in Django with the fields field_a and field_b. I have a list in python with tuples of the form (a,b)
I want to get all instances of the Django model where both fields are in the Python list.
If there was only one field, this would be simple:
my_filter_list = [a1, a2, a3]
ModelNameHere.objects.filter(field_a__in=my_filter_list)
But for multiple fields, this does not work
my_filter_list = [(a1, b1), (a2, b2), (a3, b3)]
ModelNameHere.objects.filter( ? )
Is there a way to check both fields at the same time?
Alternatively, is there a way to turn my_filter_list into a temporary table so that I can join that table with ModelNameHere using both field_a and field_b as the join key?
edit:
A quick addition: I have an index set on field_a, but not on field_b.
You could use a dictionary comprehension for the query kwargs and use a pipe operator for OR operation on querysets.
query_fields = ({ 'field_a': value_a, 'field_b': value_b } for value_a, value_b in my_filter_list)
queryset = ModelNameHere.objects.none()
for query_kwarg in query_fields:
queryset |= ModelNameHere.objects.filter(**query_kwarg)
queryset = queryset.distinct()