Django ImageField将callable传递给upload_to

9-b*_*its 4 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
Run Code Online (Sandbox Code Playgroud)

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

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


Mar*_*mro 2

您可以使用staticmethod装饰器来定义upload_to类的内部(作为静态方法)。然而,与典型的解决方案相比,它没有真正的好处,典型的解决方案是在类定义之前定义 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)
Run Code Online (Sandbox Code Playgroud)