1

I have a django model with a boolean field named status

a normal query goes like:

MyModel.objects.filter(status=True)

but in some cases , I need to use this way:

fieldname = 'status'
MyModel.objects.filter(${fieldname}=True) # wrong syntax

how to write this. thanks

kampfe20
  • 33
  • 4
  • You can use django-filter if you have many variables that you need to manage. https://django-filter.readthedocs.io/en/master/guide/usage.html – Peter Bae May 02 '20 at 06:52

1 Answers1

2

Simply,

fieldname = 'status'
MyModel.objects.filter(**{fieldname:True})
JPG
  • 82,442
  • 19
  • 127
  • 206
  • Thanks. i just don't really understand this `**` syntanx – kampfe20 May 02 '20 at 06:56
  • 1
    You can read more regarding the same here about that concept, [What does ** (double star/asterisk) and * (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – JPG May 02 '20 at 06:57
  • 1
    In short, this is what we call ***dictionary unpacking*** – JPG May 02 '20 at 06:58
  • Is there a way to do it without including `True`? Just `fieldname` as variable. – Ulvi Sep 27 '20 at 14:52
  • Here the `True` is the value to be filtered, you can use any value – JPG Sep 27 '20 at 14:58