0
我想在ImageField的rest服務upload_to方法中動態創建子文件夾/ MEDIA /中的子文件夾,名爲「{0} _ {1}」。format user_id,task_id)。修改ImageField upload_to方法以動態工作
文件和task_id將從POST請求中進行。現在,創建子文件夾所需的變量是空的。我堅信我不能保存實例時不能使用task_id。
問題是如何創建我的子文件夾?
請求示例看起來像這樣:
{
file_location: binary_file,
task_id: 15
}
serializers.py
class PostProcessingRawFilesSerializer(serializers.ModelSerializer):
class Meta:
model = ProcessingRawFilesItem
fields = (
'id',
'file_location',
'task_id'
)
def create(self, validated_data):
task_id_data = validated_data.pop('task_id')
task = Task.objects.get(pk=task_id_data)
raw_image = ProcessingRawFilesItem(task_id=task, **validated_data)
return raw_image
models.py
def user_directory_path(instance, filename):
task_id = instance.task_id
user_id = Task.objets.get(pk=task_id).owner_id
return '{0}_{1}/{2}'.format(user_id, task_id, filename)
class ProcessingRawFilesItem(models.Model):
id = models.AutoField(primary_key=True)
file_location = models.ImageField(upload_to=user_directory_path)
task_id = models.ForeignKey(Task, related_name='processing_raw_files', on_delete=models.CASCADE, null=True, blank=True)
提前感謝!