Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard in Django (Objects.filter)

Tags:

django

Is there a wildcard character in Django to use in an Objects.filter?

For example, is there a character that is the equivalent of doing this:

Prices.objects.filter(a = example1
                     ,b = example2
                    #,c = example3
)

i.e. instead of commenting out c, could I not put c = WILDCARD or c = *... you get the jist. Thank you.

EDIT: As in, if you've got a big list of attributes that can be searched for and you only want to search a select few, you aren't exactly going to have loads of functions that doing those specific searches. I need some kind of character that tells Django and then to SQL "this field doesnt matter, i want everything here"... not including the field (like in the example) just creates a shedload of functions.

like image 833
Federer Avatar asked Dec 04 '22 14:12

Federer


2 Answers

try using contains and icontains.

Here is an example:

Foo.objects.filter(name__icontains = 'hello') #fetches all whose name field contains 'hello'
like image 155
shanyu Avatar answered Dec 19 '22 19:12

shanyu


The only thing to do is a dict of attributes names and values that you dynamically filter with:

filters = {"a": "example1", "b": "example2", "c": "example3" }
prices = Prices.objects.filter(**filters)

Then you set the filters dict at runtime, add or remove key/val pairs as appropriate. That **filters is a keyword argument. Check here for more info:

http://www.nomadjourney.com/2009/04/dynamic-django-queries-with-kwargs/

like image 24
Gabriel Ross Avatar answered Dec 19 '22 19:12

Gabriel Ross