django选择字段的默认值 [英] default value for django choice field

查看:174
本文介绍了django选择字段的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设类照片是持有包含选择字段和其他属性的照片:

 类照片(model.Model):
ONLYME ='O'
FRIENDS ='F'
PUBLIC ='P'
选择=(
(ONLYME,我 ),
(FRIENDS,朋友),
(PUBLIC,Public),


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

现在,如何将照片的默认值或初始值设置为显示中的好友属性?

解决方案

使用 default 属性:

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

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


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

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?

解决方案

Use the default attribute:

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

or

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

这篇关于django选择字段的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆