The REGEX and IREGEX operators were added in Django 1.0 and I'm sure you can think of fancier ways of doing word delimiting and things like that but this was all I needed to make a user-friendly autocomplete search function.
1 2 3 4 5 6 7 8 9 10 11 12 13 | # Will find things like "Art Council", "Artists Ltd", ...
Client.objects.filter(name__istartswith="art")
# ...but won't find "The Art Council", "United Artists", ...
# This will:
Client.objects.filter(name__icontains="art")
# ...but will find things like "Lartistic plc", "Bart Simpson"
# which is not suitable for, say, an autocomplete feature
# Use this instead:
Client.objects.filter(name__iregex=r"(^|'| )art+")
# Will find things like "The Artists", "Art Uni", "Le d'Artis" but not "Bart"
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
I sugget you to use the \b boundary:
Client.objects.filter(name__iregex=r"\bart")
so you can also match "(artist", "{article", ...
#
Using the
\b
can be troubling. Remember the regular expression has to be turned into SQL.In fact I think
\b
works on SQLite but not on PostgreSQL.#
Please login first before commenting.