Sandeep Balagopal
Sandeep Balagopal

Reputation: 1983

Django queryset keyword from string

This is my model

class Mymodel(models.Model):
  title = models.CharField(max_length=150)
  author = models.CharField(max_length=150)

I have a json like this stored in db q = {"field_name": "title", "value":"django"} and this is what I am trying to do.

Mymodel.objects.filter(q["field_name"]=q["value"])

It is not working. Getting the error

SyntaxError: keyword can't be an expression

How can i make this working ? I have tried things like

Mymodel.objects.filter(getattr(event_model, q["field_name"])=q["value"])

It is possible to make it work like many if elif conditions like below but the code becomes ugly. Is there any cleaner way to do this ?

if q["field_name"] == "title":
  Mymodel.objects.filter(title=q["value"])
elif q["field_name"] == "author":
  Mymodel.objects.filter(author=q["value"])

Upvotes: 1

Views: 239

Answers (1)

JPG
JPG

Reputation: 88459

You can use the dictionary unpacking technique as,

q = {"field_name": "title", "value": "django"}

Mymodel.objects.filter(**{q["field_name"]: q["value"]})

Upvotes: 3

Related Questions