How to access Django's field.choices?

DjangoDjango Models

Django Problem Overview


Is there a way (without using a form) to access a model fields choices value?

I want to do something like field.choices and get the list of values either in a view or template.

Django Solutions


Solution 1 - Django

Sure. Just access the choices attribute of a Model field:

MyModel._meta.get_field('foo').choices
my_instance._meta.get_field('foo').choices

Solution 2 - Django

If you're declaring your choices like this:

class Topic(models.Model):

    PRIMARY = 1
    PRIMARY_SECONDARY = 2
    TOPIC_LEVEL = ((PRIMARY, 'Primary'),
                  (PRIMARY_SECONDARY, 'Primary & Secondary'),)

    topic_level = models.IntegerField('Topic Level', choices=TOPIC_LEVEL,
            default=1)

Which is a good way of doing it really. See: http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/

Then you can get back the choices simply with Topic.TOPIC_LEVEL

Solution 3 - Django

I think you are looking for get_fieldname_display() function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question9-bitsView Question on Stackoverflow
Solution 1 - DjangoYuji 'Tomita' TomitaView Answer on Stackoverflow
Solution 2 - Djangosuper9View Answer on Stackoverflow
Solution 3 - DjangoJingoView Answer on Stackoverflow