使用通用关系的动态upload_to函数的Django Image模型

问题描述 投票:2回答:2

我正在创建一个Image模型,其他模型将通过泛型关系使用它。例如,Newsposts和事件将有图像。下面是示例图像模型

class Image(models.Model):
   description = models.CharField(max_length=500, null=True, blank=True)
   image = models.ImageField(upload_to=get_storage_path)

   content_type=models.ForeignKey(ContentType,on_delete=models.CASCADE)
   object_id = models.PositiveIntegerField()
   content_object = GenericForeignKey()

这会将图像存储在一个目录中。然而问题是我无法弄清楚如何编写动态upload_to函数,将图像存储在相应的目录中,例如images/news/images/events

python django django-models image-uploading django-generic-relations
2个回答
2
投票

upload_to处理程序采用two argumentsinstancefilename。您可以检查instance以找出与该对象关联的内容类型:

def get_storage_path(instance, filename):
    # This is just an example - you'll need to use the right name
    # depending on the model class.
    if instance.content_type.model == 'news':
         # Generate filename here
    else:
         # Generate different file name here

1
投票

如果您需要在多个位置保存一个文件:Checkout Django Custom Storages

如果您只需要根据相关对象动态设置upload_to文件夹:Here是一个可能的重复线程,可以回答您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.