How to get choices field from django models in a list?
Question:
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.
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’]
[choice[1] for choice in OPTIONS]
get
['COOL', 'WARM']
Hint
We usually don’t make choices like this
Not preferred:
OPTIONS = (
('COOL', 'COOL'),
('WARM', 'WARM'),
)
I usually prefer this :
OPTIONS = (
('0', 'COOL'),
('1', 'WARM'),
)
and make max_length =1
or two if choices more than 9
verification_STATUS = (
(‘Not Verified’, ‘Not Verified’),
(‘Verified’, ‘Verified’),
(‘Wrong’, ‘Wrong’),
)
MyModel.verification_STATUS
Answer:
((‘Not Verified’, ‘Not Verified’), (‘Verified’, ‘Verified’), (‘Wrong’, ‘Wrong’))
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.
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’]
[choice[1] for choice in OPTIONS]
get
['COOL', 'WARM']
Hint
We usually don’t make choices like this
Not preferred:
OPTIONS = (
('COOL', 'COOL'),
('WARM', 'WARM'),
)
I usually prefer this :
OPTIONS = (
('0', 'COOL'),
('1', 'WARM'),
)
and make max_length =1
or two if choices more than 9
verification_STATUS = (
(‘Not Verified’, ‘Not Verified’),
(‘Verified’, ‘Verified’),
(‘Wrong’, ‘Wrong’),
)
MyModel.verification_STATUS
Answer:
((‘Not Verified’, ‘Not Verified’), (‘Verified’, ‘Verified’), (‘Wrong’, ‘Wrong’))