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

4

8

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.

Hogen answered 8/7, 2021 at 12:28 Comment(0)
B
15

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).

Broucek answered 8/7, 2021 at 12:31 Comment(0)
B
1

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']

Blowtorch answered 30/9, 2021 at 14:21 Comment(0)
C
0
[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

Congregational answered 25/10, 2022 at 9:14 Comment(0)
O
0

This one also would work.
class:

class Options(models.TextChoices):
    OPTION1 = 'option_1'
    OPTION2 = 'option_2'

    def __str__(self):
        return self.value

code:

print(f'Options.names: {Options.names}')
print(f'Options.values: {Options.values}')

output:

Options.names: ['OPTION1', 'OPTION2']
Options.values: ['option_1', 'option_2']
Ogden answered 19/7, 2024 at 3:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.