且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

django - 如何将实际图像文件从一个模型复制到另一个模型?

更新时间:2023-11-27 21:26:22

所以我知道这个问题已经很老了,但希望这个答案对某人有所帮助...

so I know this question is pretty old, but hopefully this answer help someone...

我这样做的方法是将照片上传到建议模型的正确路径:

My approach for doing this, uploading the photo to the proper path for the suggested model, is:

from django.core.files.base import ContentFile

picture_copy = ContentFile(original_instance.image.read())
new_picture_name = original_instance.image.name.split("/")[-1]
new_instance.image.save(new_picture_name, picture_copy)

请检查在我的情况下,新名称是否与文件名相同,但要在新模型图像字段的路径中更新.在您的情况下,根据您在get_upload_file_name"中的内容,它可能会再次导致相同的路径(因为在两个类中都使用).您也可以创建一个新的随机名称.

Please check that in my case, the new name is just the same file name, but to be updated in the new model image field's path. In your case, depending on what you have inside "get_upload_file_name" it could leads to the same path again (since is used in both classes). Also you can create a new, random name.

希望这对某人有帮助 =)

Hope this helps someone =)