Django filter multiple columns with a list of tuples

django-models, sql

Solution

Yes, but only* using the `where` parameter of `extra`: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra

Something like this should do:

Simple.objects.extra(where=['(a,b) in %s' % your_list])

*If you create a custom database type you should be able to define custom operators, so... might be able to work around it. I'll google a bit :)

Problem

I have a simple model with 2 fields: ``` class Simple(Model) class Meta: index_together = True a = IntField() b = IntField() ``` I would like to generate an SQL query for tuples of values for `a,b`. e.g. ``` select * from SimpleModel where (a,b) in ((1,1), (4,8), ...) ``` I know how to create something like: ``` select * from SimpleModel where ((a = 1 and b = 1) or (a = 4 and b = 8)) ``` Which is logically the same, but I think my DB has a problem when the number of possible values is very big (I am using Postgresql), also the query itself is much longer so it's heavier on the network, and probably harder for it to analyze and read it correctly (i.e. use the composite index in this case). So, the question is, can I get Django to create the query in the first form? Thanks!

Original source

Related problems