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
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
CodePudding user response:
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. Here, the max length is set to 10 as the longest value to be inserted in the field (aquamarine) is 10 characters long.
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)
CodePudding user response:
max length should be 10, because aquamarine is the biggest string and has 10 characters. try this: chat_styles = models.CharField(max_length=10, choices=CHAT_STYLES, default='purple')