简体   繁体   English

如何从列表中的 django 模型中获取选择字段?

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

I have a model having choices field.我有一个 model 有选择字段。 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.我想要列表中的选项值,如 ['COOL','WARM'],如何实现它,我尝试了类似 My_Model.options 的东西,但它不起作用。

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).如果您想要该值(为该选择呈现的部分),请使用c[1]

I checked the above code but it's giving me error on .field我检查了上面的代码,但它在.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如果选择超过 9,则使max_length =1或 2

verification_STATUS = ( ('Not Verified', 'Not Verified'), ('Verified', 'Verified'), ('Wrong', 'Wrong'), ) verification_STATUS = ( ('未验证', '未验证'), ('已验证', '已验证'), ('错误', '错误'), )

MyModel.verification_STATUS我的模型.verification_STATUS

Answer: (('Not Verified', 'Not Verified'), ('Verified', 'Verified'), ('Wrong', 'Wrong'))答案:(('未验证','未验证'),('已验证','已验证'),('错误','错误'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM