One step up from __icontains

 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. Annotate queryset with comment count by fivethreeo 5 years, 6 months ago
  2. get_queryset_or_404 by mattpdx 5 years, 11 months ago
  3. Changing queryset of a ModelChoiceField by mimog 2 years, 9 months ago
  4. Custom Model Manager Chaining by hunterford 3 years, 9 months ago
  5. Check condition in Form Queryset by felipecruz 2 years, 4 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.

#

(Forgotten your password?)