Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#2458 closed defect (fixed)

[patch] Backslashes in LIKE queries are not escaped

Reported by: tom@… Owned by: adrian
Component: Database layer (models, ORM) Version:
Severity: major Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


Say you have a model called MyModel with a TextField called text and want to get all objects where text contains a backslash. The following query, however, doesn't return anything:


This query does:


Here is a patch that fixes the problem:

Index: django/db/models/fields/
--- django/db/models/fields/ (revision 3496)
+++ django/db/models/fields/ (working copy)
@@ -20,7 +20,7 @@
 BLANK_CHOICE_NONE = [("", "None")]
 # prepares a value for use in a LIKE query
-prep_for_like_query = lambda x: str(x).replace("%", "\%").replace("_", "\_")
+prep_for_like_query = lambda x: str(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_")
 # returns the <ul> class for a given radio_admin value
 get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')

Change History (3)

comment:1 Changed 9 years ago by anonymous

  • Component changed from Admin interface to Database wrapper

comment:2 Changed 9 years ago by anonymous

  • Summary changed from Backslashes in LIKE queries are not escaped to [patch] Backslashes in LIKE queries are not escaped

comment:3 Changed 9 years ago by adrian

  • Resolution set to fixed
  • Status changed from new to closed

(In [3552]) Fixed #2458 -- DB API now properly escapes backslashes, so you don't have to double-escape them. Thanks, tom@…

Note: See TracTickets for help on using tickets.
Back to Top