Django ImageField将callable传递给upload_to

时间:2012-02-01 04:08:16

标签: django django-models

我正在尝试将自定义upload_to函数传递给我的模型imageField,但我想将该函数定义为模型函数....这可能吗?

class MyModel(models.Model):
    ...
    image = models.ImageField(upload_to=self.get_image_path)
    ...

    def get_image_path(self, filename):
        ...
        return image_path

现在我知道我不能用“自我”来引用它,因为那时候自己不存在......有没有办法做到这一点?如果不是 - 定义该功能的最佳位置在哪里?

2 个答案:

答案 0 :(得分:8)

所以只需删除“@classmethod”,Secator的代码就可以了。

class MyModel(models.Model):

    # Need to be defined before the field    
    def get_image_path(self, filename): 
        # 'self' will work, because Django is explicitly passing it.
        return filename

    image = models.ImageField(upload_to=get_image_path)

答案 1 :(得分:2)

您可以使用staticmethod装饰器来定义类内部的upload_to(作为静态方法)。 Hovever它没有优于典型解决方案的真正好处,它在类定义like here之前定义了get_image_path。)

class MyModel(models.Model):

    # Need to be defined before the field
    @classmethod       
    def get_image_path(cls, filename): 
        # 'self' will work, because Django is explicitly passing it.
        return filename

    image = models.ImageField(upload_to=get_image_path)