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.
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.
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.
[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.
Sure. Just access the choices
attribute of a Model field:
MyModel._meta.get_field('foo').choices
my_instance._meta.get_field('foo').choices
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With