【问题标题】:How to copy paste FileField?如何复制粘贴 FileField?
【发布时间】: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


    【解决方案1】:

    尝试制作文件字段的深层副本,我发现了一个可能有用的链接:Force deep copy of Django FileField object (mainly new file itself)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多