Force deep copy of Django FileField object (mainly new file itself)

两盒软妹~` 提交于 2020-01-05 18:36:22

问题


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:


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.



来源:https://stackoverflow.com/questions/29270812/force-deep-copy-of-django-filefield-object-mainly-new-file-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!