django选择字段的默认值

时间:2022-10-16 18:10:59

Suppose class Photo is to hold photos having choice fields and other attributes:

假设类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)

Now, how do I set the default or initial value of a photo to 'Friends' in the display attribute?

现在,如何在display属性中将照片的默认值或初始值设置为“朋友”?

2 个解决方案

#1


14  

Use the default attribute:

使用默认属性:

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

or

要么

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

#2


2  

You could just set the default attribute:

您可以设置默认属性:

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

Reference.

参考。

#1


14  

Use the default attribute:

使用默认属性:

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

or

要么

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

#2


2  

You could just set the default attribute:

您可以设置默认属性:

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

Reference.

参考。