gpt4 book ai didi

django - 将回调作为upload_to 传递给FileField

转载 作者:行者123 更新时间:2023-12-04 11:46:55 24 4
gpt4 key购买 nike

我有一个抽象模型类 UploadItem 用于处理上传的文件。我希望每个子类都能够定义 upload_to 路径。为此,我将回调传递给 FileField 的构造函数。

这是一个例子:

class UploadItem(models.Model):
file = models.FileField(upload_to=UploadItem.get_directory)


class Meta:
abstract = True
# I want videos to be storred in 'videos/' directory
class Video(UploadItem):
def get_directory(self, instance, filename):
return 'videos/'

但这不起作用,我收到此错误:
file = models.FileField(upload_to=UploadItem.get_directory) 
NameError: name 'UploadItem' is not defined

最佳答案

考虑到在评估时,错误是很自然的

file = models.FileField(upload_to=UploadItem.get_directory) 
UploadItem类尚未定义。您可以执行以下操作以使其工作:
def get_directory():
pass

class UploadItem(models.Model):
file = models.FileField(upload_to=get_directory)

class Meta:
abstract = True

但这并不能解决您所有的问题。添加(或覆盖)方法 get_directoryVideo类不会改变 upload_to file 的属性(property)模型的属性。

更新

documentationupload_to可以是一个可调用的。

This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system.



鉴于此,我们可以编写一个自定义回调函数,如下所示:
categories_and_paths = { 'video': 'videos/', 'photo': 'photos/' } # etc.
def get_directory(instance, filename):
category = instance.category
return categories_and_paths.get(category, '')
Instance这里将是相应模型的实例。为此,每个模型实例都应该有一个类别字段。我们可以在模型的主体中添加一个。
class Video(UploadItem):
category = 'video'

关于django - 将回调作为upload_to 传递给FileField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3669830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com