我希望Django模型字段只能有两个可能的值

Taj*_*ngh 4 django

class Proposta(models.Model):
     descrizione = models.TextField()
     titolo = models.CharField(max_length=200)
     richiedibile = models.BooleanField(default=False)
     inRichiesta = models.BooleanField(default=False)
     archiviata = models.BooleanField(default=False)

     # tesi or AP
     tipologia = models.CharField(max_length=50)
Run Code Online (Sandbox Code Playgroud)

我希望“ tipologia”字段只能有两个可能的值:“ tesi”或“ AP”。换句话说,我希望该字段看起来像一个列表,用户可以在其中选择所需的值。

Ala*_*air 6

choices在Charfield中使用参数:

TIPOLOGIA_CHOICES = [
    ("tesi", "tesi"),
    ("AP", "AP"),
]

class Proposta(models.Model):
    ...
    tipologia = models.CharField(max_length=50, choices=TIPOLOGIA_CHOICES)
Run Code Online (Sandbox Code Playgroud)

  • 还记得添加默认值或使其可为空 (2认同)