简体   繁体   English

如何从列表中选择默认选择字段

[英]How to choose default choice field from a list

In a django model I need to set a default for a choice field but I don't get how to do the syntax part在 django model 我需要为选择字段设置默认值,但我不知道如何执行语法部分

This is the list这是清单

CHAT_STYLES = [
    ("orange", "orange"),
    ("purple", "purple"),
    ("aquamarine", "aquamarine"),
    ("aqua", "aqua"),
    ("beige", "beige"),
    ("yellow", "yellow"),
    ("green", "green"),
    ("blue", "blue")
]

I tried to do like this我试着这样做

chat_styles = models.CharField(max_length=2, choices=CHAT_STYLES, default=CHAT_STYLES."purple")

or或者

 chat_styles = models.CharField(max_length=2, choices=CHAT_STYLES, default=CHAT_STYLES["purple"])

but it didn't work但它没有用

You can use a TextChoices model to name all your choices and then use a name from those choices to set a default in the related model.您可以使用 TextChoices model 命名所有选项,然后使用这些选项中的名称在相关 model 中设置默认值。 Here, the max length is set to 10 as the longest value to be inserted in the field (aquamarine) is 10 characters long.在这里,最大长度设置为 10,因为要插入字段(海蓝宝石)的最长值是 10 个字符长。

class ChatStyleModel(models.TextChoices):
    orange = ("orange", "orange")
    purple = ("purple", "purple")
    aquamarine = ("aquamarine", "aquamarine")
    aqua = ("aqua", "aqua")
    beige = ("beige", "beige")  
    yellow = ("yellow", "yellow")
    green = ("green", "green")
    blue = ("blue", "blue")

class ChatModel(models.Model):
    chat_styles = models.CharField(max_length=10, choices=ChatStyleModel.choices, default=ChatStyleModel.purple)

max length should be 10, because aquamarine is the biggest string and has 10 characters.最大长度应该是 10,因为 aquamarine 是最大的字符串并且有 10 个字符。 try this: chat_styles = models.CharField(max_length=10, choices=CHAT_STYLES, default='purple')试试这个:chat_styles = models.CharField(max_length=10,choices=CHAT_STYLES,default='purple')

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

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