4

我正在创建一个图像模型,其他模型将通过通用关系使用该模型。例如,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.

4

2 回答 2

2

处理程序upload_to接受两个instance参数和filename。您可以检查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
于 2017-12-17T02:52:48.920 回答
1

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

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

于 2017-12-17T02:13:40.743 回答