Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Django's field.choices?

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.

like image 426
9-bits Avatar asked Aug 28 '12 19:08

9-bits


People also ask

How do Django choices work?

Choices limits the input from the user to the particular values specified in models.py . If choices are given, they're enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field.

Is there a list field in Django?

If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine library, there is a built in ListField that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.

What are Django options?

[The OPTIONS ] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.


2 Answers

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

MyModel._meta.get_field('foo').choices
my_instance._meta.get_field('foo').choices
like image 107
Yuji 'Tomita' Tomita Avatar answered Oct 16 '22 18:10

Yuji 'Tomita' Tomita


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

like image 13
super9 Avatar answered Oct 16 '22 18:10

super9