59π
β
This is pretty much ok to import your choice mapping FILE_STATUS_CHOICES
from models and use it to get Pending
by P
:
from my_app.models import FILE_STATUS_CHOICES
print dict(FILE_STATUS_CHOICES).get('P')
get_FIELD_display()
method on your model is doing essentially the same thing:
def _get_FIELD_display(self, field):
value = getattr(self, field.attname)
return force_text(dict(field.flatchoices).get(value, value), strings_only=True)
And, since there is a flatchoices
field on the model field, you can use it with the help of _meta
and get_field_by_name()
method:
choices = f._meta.get_field_by_name('name')[0].flatchoices
print dict(choices).get('P')
where f
is your model instance.
Also see:
π€alecxe
0π
I recommend using Choice
from django-model-utils
: https://django-model-utils.readthedocs.io/en/latest/utilities.html#choices.
I use it in every my models if I need choice field. See examples, it has excellent options.
π€Ibrohim Ermatov
- [Django]-Django error β matching query does not exist
- [Django]-Django "login() takes exactly 1 argument (2 given)" error
- [Django]-DatabaseError: current transaction is aborted, commands ignored until end of transaction block?
Source:stackexchange.com