如何复制粘贴文件域?

2024-04-23 21:57:41 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我如何将文件从窗体上载到后端的FileField:

the_file    = request.FILES['newProfilePicture']
the_customer = Customer.objects.first()
the_customer.profile_picture = the_file
the_customer.save()

但问题是,如何获取该文件字段,然后将其“复制粘贴”到另一个具有不同“upload\u to”数据的对象?你知道吗

客户对象:

class Customer( models.Model ):
    profile_picture = models.FileField(upload_to='uploads/customer/%Y/%m/%d/')

客户可选择的对象:

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对象的数据。有没有办法“复制粘贴”数据呢?你知道吗

我试着做深度复制,但失败了?你知道吗

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()

Tags: the对象newobjectsmodelssavecustomerprofile