3

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?
Chris W.
  • 37,583
  • 36
  • 99
  • 136
  • This is also related: http://stackoverflow.com/questions/310732/in-django-how-does-one-filter-a-queryset-with-dynamic-field-lookups – S.Lott May 05 '11 at 21:47

1 Answers1

9
query_specifier = {
    'name__iexact': 'foobar'
}
query_set = MyModel.objects.filter(**query_specifier)
Dan Breen
  • 12,626
  • 4
  • 38
  • 49
  • This works because Django *is* python, and **query_specifier will be unpacked. Here's a related post about kwargs: http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python – Zach Kelling May 05 '11 at 20:14