Django的FileField或物体的力深拷贝(主要是新的文件本身)(Force deep cop

2019-10-22 09:15发布

我有这样的模式:

class DocVersion(Commentable):

    name = models.CharField(
        'Version',
        max_length=100,
    )

    docfile = models.FileField(
        'File',
        upload_to='content/%Y/%m/%d/%H/%M/%S',
    )

    created = models.DateTimeField(
        'Created',
        auto_now_add=True,
    )

    creater = models.ForeignKey(
        User,
    )

class Document(DocumentBase):

    #..... blah .....

    versions = models.ManyToManyField(
        DocVersion,
    )

在一个视图中的功能,我有这个功能做DocVersion像这样的深层副本:

def cp_document(transfer_object_id, parent_folder_id):
    document = Document.objects.get(pk=transfer_object_id)
    versions = []
    for version in document.versions.all():
        version.pk = None
        version.save()
        versions.append(version)
    document.pk = None
    document.parent = Folder.objects.get(pk=parent_folder_id)
    document.save()
    for version in versions:
        document.versions.add(version)
    document.save()

当我做了版本cp_document()的副本,它创建一个新的领域,但仍保持了该版本的文件中的字段相同的路径。 是否有可能引发DocVersion创建一个新的文件名和路径(最好使用目录结构相同的时间格式正如我在upload_to参数已指定)的新版本? 或者是有一些其他的方式可能做到这一点?

Answer 1:

想出了这个:

from django.core.files.base import ContentFile

...

def cp_document(user, transfer_object_id, parent_folder_id):

    document = Document.objects.get(pk=transfer_object_id)
    versions = []

    for version in document.versions.all():

        dv = DocVersion()
        dv.name = version.name
        dv.docfile = ContentFile(version.docfile.read())
        dv.docfile.name = version.docfile.name
        dv.creater = user
        dv.save()
        versions.append(dv)

    document.pk = None
    document.parent = Folder.objects.get(pk=parent_folder_id)
    document.save()

    for version in versions:
        document.versions.add(version)
    document.save()

希望这可以帮助别人。



文章来源: Force deep copy of Django FileField object (mainly new file itself)