Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a string as the argument to a Django filter query

I'm trying to do a django query, but with the possibility of several different WHERE parameters. So I was thinking of doing something like:

querystring = "subcat__id__in=[1,3,5]" Listing.objects.filter(querystring) 

Here Listing is defined in my model, and it contains the Many-To-Many field subcat. However, that raises a ValueError because filter doesn't accept a string as its argument. Is there a way in Python to have a string evaluated as just its contents rather than as a string? Something like a print statement that prints the value of the string inline rather than to the standard output.

By the way, the reason I don't just do

querystring = [1,3,5] Listing.objects.filter(subcat__id__in=querystring) 

is that I'm not always filtering for subcat__id, sometimes it's one or several other parameters, and I'd rather not have to write out a bunch of separate queries controlled by if statements. Any advice is much appreciated.

like image 927
danny Avatar asked Nov 28 '10 00:11

danny


People also ask

How can I filter a Django query with a list of values?

The sql query will be like SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9] which is not true. You have to use in operator for this so you query will be like SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9) for that Django provide __in operator.

How do I do an and filter in a Django query?

filter(name=x or name= y) but this answer will give first = allobjects. filter(name=x) then filter first. filter(name=y). Hope you guys get it.

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


2 Answers

Perhaps...

filter_dict = {'subcat__id__in': [1,3,5]} Listing.objects.filter(**filter_dict) 
like image 127
Josh Smeaton Avatar answered Sep 20 '22 18:09

Josh Smeaton


Listing.objects.filter(**{"subcat__id__in": ast.literal_eval("[1,3,5]")}) 
like image 32
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 18:09

Ignacio Vazquez-Abrams