简体   繁体   English

一旦设置为 null,如何在 Django model 中使用默认值?

[英]How to use default value in Django model once set to null?

I have this model in my django app:我的 django 应用程序中有这个 model:

class Person(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(blank=True, upload_to='images', default='default/static/image/here')

    def __str__(self):
        return self.name

When making a Person object, if left empty, the "image" is set to a default value, but later, if the user decides to remove his image, his image will no longer be set to default but to NULL instead.在制作 Person object 时,如果留空,“图像”将设置为默认值,但稍后,如果用户决定删除他的图像,他的图像将不再设置为默认值,而是设置为 NULL。 How can I make it so that whenever image is NULL again, it automatically brings back the default value?我怎样才能使图像再次为 NULL 时,它会自动恢复默认值?

When image will be changed, ImageField won't be Null.更改图像时,ImageField 不会是 Null。 You can just set default image.您可以设置默认图像。 if user want to remove his image, default image again will appear.如果用户想删除他的图像,默认图像会再次出现。

You can modify the save method that checks if the ImageField is Null您可以修改检查 ImageField 是否为 Null 的保存方法

class Person(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(blank=True, upload_to='images', default='default/static/image/here')

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.image:  #here
            self.image = 'default/static/image/here'
        super(Person, self).save(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM