Django模型中的类属性继承

art*_*nik 1 python django django-models

有两种型号:

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'
Run Code Online (Sandbox Code Playgroud)

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

        self.image.upload_to = 'images/news/%Y/%m/%d'
Run Code Online (Sandbox Code Playgroud)

Roh*_*han 6

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

在models.py中

#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)
Run Code Online (Sandbox Code Playgroud)