Force deep copy of Django FileField object (mainly

2019-07-29 13:15发布

I have this model:

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

In a function in a view, I have this function to do a deep copy of the DocVersion like so:

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

When I do the copy for the versions in cp_document(), it does create a new field but still keeps the same path for the version's file field. Is it possible to trigger DocVersion to create a new version with a new file and path (ideally using the same time formats for directory structure as I have designated in the upload_to parameter)? Or is there some other way to do this possibly?

1条回答
淡お忘
2楼-- · 2019-07-29 13:20

Came up with this:

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

Hope this helps someone.

查看更多
登录 后发表回答