How to get choices field from django models in a list?

Viewed 5734

I have a model having choices field. I want to fetch the choices options in a list.

How can I achieve that?

OPTIONS = (
    ('COOL', 'COOL'),
    ('WARM', 'WARM'),
)
class My_Model(models.Model):
     options = models.CharField(max_length=20, choices=OPTIONS, default=None,blank=True, null=True)

I want options values in a list like ['COOL','WARM'], How to achieve it, I tried something like My_Model.options but it is not working.

2 Answers

You can obtain the data with:

>>> My_Model.options.field.choices
(('COOL', 'COOL'), ('WARM', 'WARM'))

you thus can get a list of keys with:

>>> [c[0] for c in My_Model.options.field.choices]
['COOL', 'WARM']

and use c[1] if you want the value (the part that is rendered for that choice).

I checked the above code but it's giving me error on .field

So i tried other code and that code is working for me.

[OPTIONS[c][0] for c in range(len(OPTIONS))]

['COOL', 'WARM']

Related