【发布时间】:2018-02-05 06:01:30
【问题描述】:
这就是我如何将文件从表单上传到后端的 FileField:
the_file = request.FILES['newProfilePicture']
the_customer = Customer.objects.first()
the_customer.profile_picture = the_file
the_customer.save()
但问题是,我如何获取该文件字段,然后将其“复制粘贴”到另一个具有不同“upload_to”数据的对象?
客户对象:
class Customer( models.Model ):
profile_picture = models.FileField(upload_to='uploads/customer/%Y/%m/%d/')
Customer_Alternative 对象:
class Customer_Alternative( models.Model ):
profile_picture = models.FileField(upload_to='uploads/customer-alternative/%Y/%m/%d/')
我目前的问题是,当我执行以下操作时,它只是使用相同的图片而不是“复制粘贴”到新目录:
old_customer = Customer.objects.all().first()
new_customer_alternative = Customer_Alternative( profile_picture=old_customer.profile_picture, )
new_customer_alternative.save()
因此,如果我删除该 Customer 对象上的 FileField,它也会删除 Customer_Alternative 的数据。无论如何要“复制粘贴”数据吗?
我尝试做深拷贝,但失败了?
old_customer = Customer.objects.all().first()
new_customer_alternative = Customer_Alternative( profile_picture=old_customer.profile_picture, )
new_customer_alternative.profile_picture.file = ContentFile(old_customer.profile_picture.read())
new_customer_alternative.save()
【问题讨论】:
标签: python django django-models