gpt4 book ai didi

python - Django 模型中的类属性继承

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:08 25 4
gpt4 key购买 nike

有两种模式:

class BaseImage(models.Model):
description = models.CharField(max_length=200)
image = models.ImageField(upload_to='images')

class Meta:
abstract = True

class PostImage(BaseImage):
in_text = models.BooleanField()

def __init__(self, *args, **kwargs):
super(BaseImage, self).__init__(*args, **kwargs)
self.image.upload_to = 'images/news/%Y/%m/%d'

如何在基础模型中设置 upload_to 属性?这是我的尝试不起作用:

        self.image.upload_to = 'images/news/%Y/%m/%d'

最佳答案

我可以建议的是编写函数以从实例上传到方法,例如

在模型中

#default method to get file upload path
def get_upload_to(instance, filename):
return instance.get_upload_to_path(filename)

class BaseImage(models.Model):
description = models.CharField(max_length=200)
image = models.ImageField(upload_to=get_upload_to)

class Meta:
abstract = True
#method on the class to provide upload path for files specific to these objects
def get_upload_to_path(instance, filename):
return 'images/'+filename

class PostImage(BaseImage):
in_text = models.BooleanField()

#method to provide upload path for PostImage objects
def get_upload_to_path(instance, filename):
#change date.year etc to appropriate variables
return 'images/news/%Y/%m/%d' % (date.year, date.month, date.day)

关于python - Django 模型中的类属性继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12347420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com