Chris W.
Chris W.

Reputation: 39219

Specifying Django Query Filters at Run Time

How do I specify an arbitrary Django query filter at runtime?

Normally one uses filters like so...

query_set = MyModel.objects.filter(name__iexact='foobar')

But what if I have the query filter specifier contained in a string?

query_specifier = "name_iexact='foobar'"
query_set = MyModel.objects.filter(query_specifier) # <-- This doesn't work; How can I do this?

Upvotes: 3

Views: 316

Answers (1)

Dan Breen
Dan Breen

Reputation: 12924

query_specifier = {
    'name__iexact': 'foobar'
}
query_set = MyModel.objects.filter(**query_specifier)

Upvotes: 9

Related Questions