Houman
Houman

Reputation: 66370

How to pass in the fieldname to filter in django?

Filtering in Django is pretty straight forward if you know which fieldname you are filtering for:

Entry.objects.filter(headline__startswith="What")

But if I would like to pass in the "headline" fieldname it gets more difficult:

kwargs = {request.GET['fieldname'] : request.GET['query']}
Entry.objects.filter(**kwargs)

the problem with the solution above is though, how do I pass in the __startswith in there?

Upvotes: 0

Views: 70

Answers (1)

JamesO
JamesO

Reputation: 25946

kwargs = {"%s__startswith" % (request.GET['fieldname']) : request.GET['query']}
Entry.objects.filter(**kwargs)

Upvotes: 1

Related Questions