32

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.

3 Answers 3

82

Perhaps...

filter_dict = {'subcat__id__in': [1,3,5]}
Listing.objects.filter(**filter_dict)
Sign up to request clarification or add additional context in comments.

2 Comments

@danny Accepted answer then? =P
Is it possible to do or using this pattern. e.g. Q(subcat__id__in =[1,3,5]) | Q(cat__id=9)?
9
Listing.objects.filter(**{"subcat__id__in": ast.literal_eval("[1,3,5]")})

Comments

1

You can do an OR query like this:

from functools import reduce
from operator import or_

query_as_dict = {"subcat__id__in": [1,3,5], "cat__id": 9}
query = reduce(or_, (Q(**{key: value}) for key, value in query_as_dict.items()))
Listing.objects.filter(query)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.