rz.
rz.

Reputation: 20037

Django: how to filter for rows whose fields are contained in passed value?

MyModel.objects.filter(field__icontains=value) returns all the rows whose field contains value. How to do the opposite? Namely, construct a queryset that returns all the rows whose field is contained in value?

Preferably without using custom SQL (ie only using the ORM) or without using backend-dependent SQL.

Upvotes: 1

Views: 103

Answers (1)

Jordan Reiter
Jordan Reiter

Reputation: 20992

field__icontains and similar are coded right into the ORM. The other version simple doesn't exist.

You could use the where param described under the reference for QuerySet.

In this case, you would use something like:

MyModel.objects.extra(where=["%s LIKE CONCAT('%%',field,'%%')"], params=[value])

Of course, do keep in mind that there is no standard method of concatenation across DMBS. So as far as I know, there is no way to satisfy your requirement of avoiding backend-dependent SQL.

If you're okay with working with a list of dictionaries rather than a queryset, you could always do this instead:

qs = MyModel.objects.all().values()
matches = [r for r in qs if value in r[field]]

although this is of course not ideal for huge data sets.

Upvotes: 3

Related Questions