Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 379
Danny Brown Avatar asked Jul 25 '14 20:07

Danny Brown


People also ask

Can you filter a QuerySet?

Working with Filter Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters.

What is difference between contains and Icontains in django?

Definition and Usage The contains lookup is used to get records that contains a specified value. The contains lookup is case sensitive. For a case insensitive search, use the icontains lookup.

Can you filter by property django?

Django-property-filter is an extension to django-filter and provides functionality to filter querysets by class properties. It does so by providing sub-classes for Filters and Filtersets to keep existing django-filter functionality. For more details and examples check the documentation.


1 Answers

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

like image 128
Aaron Lelevier Avatar answered Oct 28 '22 23:10

Aaron Lelevier