I’m looking for a way to do this:
qs = MyModel.objects.filter(mystring__like="____10____")
#Which would create a sql clause
... LIKE '____10____'
instead of behave like this:
qs = MyModel.objects.filter(mystring__icontains="____10____")
#Which creates a sql clause
... LIKE %\_\\_\\_\\_10\\_\\_\\_\\_%
I know I can use a regex filter, but that’s substantially slower and more error prone than just using the built-in mysql wildcard feature (I’ve tested it directly in mysql, the query strings are long enough that the difference is substantial).
EDIT:
figured out how to do this with the .extra() method with madisvain’s help.
qs = MyModel.objects.extra(where=["`mystring` LIKE '____10____'"])
In terms of performance difference, 2000 random queries with the regex approach took 20.5 seconds, with this approach 2000 random queries take 6 seconds.
I didn’t even know django had this __like version. Well but according to the docs please read this!
https://docs.djangoproject.com/en/dev/topics/db/queries/#escaping-percent-signs-and-underscores-in-like-statements
You should be writing the query like this.
Or this.
Read more about the extra() method here:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra