Django Resolve Choices Class

31 views
Skip to first unread message

sebasti...@gmail.com

unread,
Aug 30, 2023, 4:11:18 PM8/30/23
to Django users
I have in my 

model.py:

class GendersChoices(models.IntegerChoices):
    M = 0, _('Male')
    F = 1, _('Female')
    N = 2, _('Gender Neutral')

class Address(models.Model):
gender = models.PositiveSmallIntegerField(choices=GendersChoices.choices, blank=True, default=GendersChoices.F, null=True,verbose_name=_('Gender'))

Now i have a entity from Address and when i make entity.gender i get a number from database. But i want when in entity are insert 2 then i want to get _('Gender Neutral') instead of 2

How i can do that?

Andréas Kühne

unread,
Aug 31, 2023, 2:04:13 PM8/31/23
to django...@googlegroups.com
If you want the string instead of the value, you just use:
entity.get_gender_display()

Django automatically adds these "magic methods" when you have fields that have choices.

You can see this in the documentation:

Regards,

Andréas


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/53c122e7-0448-4d67-9cd4-ce11ffa2ef5cn%40googlegroups.com.

Sebastian Jung

unread,
Aug 31, 2023, 2:24:55 PM8/31/23
to django...@googlegroups.com
Thank you it is working. Wonderful 

Reply all
Reply to author
Forward
0 new messages