Django选项字段的默认值

pokxtpni  于 2023-06-25  发布在  Go
关注(0)|答案(4)|浏览(144)

假设class Photo要保存具有选择字段和其他属性的照片:

class Photo(models.Model):
    ONLYME = 'O'
    FRIENDS = 'F'
    PUBLIC = 'P'
    CHOICES = (
        (ONLYME, "Me"),
        (FRIENDS, "Friends"),
        (PUBLIC, "Public"),
    )

    display = models.CharField(max_length=1, choices=CHOICES, blank=True, null=True)
    user = models.ForeignKey(User)
    description = models.TextField()
    pub_date = models.DateTimeField(auto_now=True, auto_now_add=False)
    update = models.DateTimeField(auto_now=False, auto_now_add=True)
    image = models.ImageField(upload_to=get_upload_file_name, blank=True)

现在,如何在display属性中将照片的默认值或初始值设置为"Friends"

xriantvc

xriantvc1#

使用default属性:

display = models.CharField(..., default=FRIENDS)

display = models.CharField(..., default=CHOICES[1][1])
rqenqsqc

rqenqsqc2#

您可以设置默认属性:

display = models.CharField(default='F', max_length=1, choices=CHOICES, blank=True, null=True)

参考文献。

nukf8bse

nukf8bse3#

RadioButtons有一个ChoiceField属性,那么解决方案可以是“初始”属性...示例:

from django import forms
        CHOICES = [("1", "First choice"), ("2", "Second choice")]
    
    class ContactForm(forms.Form):
        choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, initial="1")
bq8i3lrv

bq8i3lrv4#

请注意,这是一个老问题。从Django 3.0开始,规范的方法是使用models.TextChoices类。
下面是一个使用Enum函数式API的示例:

CHOICES = models.TextChoices(
    "Display", (
        ("O", "Me"),
        ("F", "Friends"),
        ("P", "Public"),
    )
)

然后你可以写

display = models.CharField(
    max_length=1, choices=CHOICES, default=CHOICES.F, blank=True, null=True
)

相关问题