Reputation: 27
I was trying to combine filtering Django data through a combination of dictionary and regular expression. So my dictionary looks like this:
dict = {key: r'.*?' + value + '.*?$'}
where I have key and value as string variables.
And I want to filter the data such that all the rows I retrieve have its key index's values contains the string value.
table.objects.all().filter(**dict)
However, this does not give me the rows I desire; in fact, it gives me no row at all while all the rows with index key should have shown. I'd appreciate any insights into what might have gone wrong here and how I can begin fixing it. Thank you!
Edit: I would prefer to use the Dictionary approach to filtering because I'm taking the keys to filter as a substring given in the URL parameters. If you think there is any other way I can retrieve the string from the URL and do something like:
table.objects.all().filter(key: r'.*?' + value '*?$' ).
I would appreciate it as well, just not sure how to do that given I only have variable key as a string!
Edit: key is "city", value is "Philadelphi", and I'm looking for rows that have index "city" = "Philadelphia", but those do not show.
Upvotes: 0
Views: 1224
Reputation: 21812
You say that key
is "city"
and value
is "Philadelphi"
, if we replace these in the query you make you basically write:
table.objects.all().filter(city= r'.*?Philadelphi*?$')
If the problem is not yet visible, then when one doesn't specify a lookup it is automatically assumed to be an exact
lookup, you instead want to either use the regex
or iregex
lookup. Also you should escape your value when you put it in a regex:
import re
key = '%s__iregex' % key
value = r'.*?%s.*?$' % re.escape(value)
dict = {key: value}
table.objects.all().filter(**dict)
Also as suggested in the comments your regex doesn't seem to be different from a contains
lookup so unless you have some different regex you should use:
key = '%s__contains' % key
dict = {key: value}
table.objects.all().filter(**dict)
Upvotes: 1