Jag hittade en lösning som bygger på @erwin-brandstetter-svaret med en anpassad sökning
from django.db.models import Lookup
from django.db.models.fields import Field
@Field.register_lookup
class EfficientInLookup(Lookup):
lookup_name = "ineff"
def as_sql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return "%s IN (SELECT unnest(%s))" % (lhs, rhs), params
Detta gör det möjligt att filtrera så här:
MyModel.objects.filter(id__ineff=<list-of-values>)