0

If I have a CharField in a Django model, and I try to filter it using a string pattern with the LIKE operator, such as:

MyModel.objects.filter(text__like='he_lo')

Django returns the error:

django.core.exceptions.FieldError: Unsupported lookup 'like' for CharField or join on the field not permitted.

However, if I use manage.py dbshell to run the raw SQL:

select * from myapp_mymodel where text like 'he_lo';

it runs just fine.

Why does Django disallow pattern matching in it's ORM even though Sqlite supports it?

Cerin
  • 60,957
  • 96
  • 316
  • 522
  • Does [this](https://stackoverflow.com/questions/18140838/sql-like-equivalent-in-django-query) answer your question? – Richard Neumann Jan 26 '22 at 23:33
  • @RichardNeumann Sort of. Django's `__contains` is a wrapper around `LIKE`, not a simple alias. – Cerin Jan 27 '22 at 00:28
  • @RichardNeumann That question also doesn't refer to Sqlite. The `__contains` postfix also doesn't seem to support SQL wildcards, even though Sqlite support them. – Cerin Jan 27 '22 at 00:43

1 Answers1

0

You can try raw query like this:

 objs = MyModel.objects.raw(
     "SELECT * FROM myapp_mymodel WHERE text LIKE %s", ['%he_lo']
 )
 for obj in objs:
    # do something
Ahtisham
  • 9,170
  • 4
  • 43
  • 57