Django: Filtering a model that contains a field that stores Regex

Danny Brown picture Danny Brown · Jul 25, 2014 · Viewed 15k times · Source

I have a field that stores REGEX patterns and I'm trying to filter the model that it is in by comparing it with a passed in variable called hostname. (Ex: Here I just hard coded the REGEX.

Sys_team.objects.filter(hostname= r'^.*\.amgr\..*')

I'm met with this error:

FieldError: Cannot resolve keyword 'hostname' into field. Choices are: alert, id, pattern, pub_date, sys_team

The hostname has the format of: xxx.amgr.xxx

Does that mean that only fields can go in the left side of the filter?And if so, is there another way to compare the two with the REGEX pattern on the left side. To reiterate, hostname is not a field.

Answer

Aaron Lelevier picture Aaron Lelevier · Jul 25, 2014

Use the Django __contains method.

So for your query:

Sys_team.objects.filter(hostname__contains='.amgr.')

__contains is Django ORM's equivalent to SQL's LIKE keyword.

Here's the docs:

https://docs.djangoproject.com/en/dev/topics/db/queries/#escaping-percent-signs-and-underscores-in-like-statements