我有这个型号:
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参数中指定的目录结构相同的时间格式)?或者还有其他方法可以做到这一点吗?
答案 0 :(得分: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()
希望这有助于某人。