Using join of temporary table as an alternative of `IN` in Django

Viewed 1230

In Django it's common to do the following

MyModel.objects.filter(id__in=[huge array])

However it's not very efficient as described in the following answer here: https://dba.stackexchange.com/questions/91247/optimizing-a-postgres-query-with-a-large-in

What would be a good way of replicating the above answer in Django given that you are using the ORM. Or would you have to drop down to raw sql for the entire query.

What I'm looking for is if you have a queryset, is there a good way of joining that queryset with a temporary table that you created (possibly in raw sql).

1 Answers

You can use the select_related option, to filter your second table(another model) that will do the in effect.

Something like this answer: Django select_related filter

I use that for large INs when its possible.

Related