Login

One step up from __icontains

Author:
peterbe
Posted:
September 8, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

aparo (on September 9, 2010):

I sugget you to use the \b boundary:

Client.objects.filter(name__iregex=r"\bart")

so you can also match "(artist", "{article", ...

#

peterbe (on September 10, 2010):

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.