简体   繁体   English

如何避免覆盖 django 模型

[英]How do I avoid overwrite in django models

I have class called AlbumImage我有一个叫 AlbumImage 的 class

class AlbumImage(models.Model):
    album = models.ForeignKey(Album, on_delete=models.PROTECT,related_name="raters")
    image = models.ImageField(upload_to="Album") 

when i upload first image called (for example) image1.png every thing in ok,,,,当我上传第一张名为(例如)image1.png 的图片时,一切正常,,,,
But if I upload another image with the same name(image1.png), and go back to the first object, I will find the second image in its place.但是如果我上传另一张同名的图片(image1.png),并将 go 返回到第一个 object,我会在它的位置找到第二张图片。

How do I avoid overwrite?如何避免覆盖?

The FileField and ImageField will detect this, and will add a random part to avoid overwriting. FileFieldImageField将检测到这一点,并将添加一个随机部分以避免覆盖。

It is only if you set it to a string, that it will take that, since then you refer to the name of a file.只有当你将它设置为一个字符串时,它才会接受它,从那时起你就引用了一个文件的名称。 But if you thus work through a ( Model )Form, or the ModelAdmin , or you pass it with a File object.但是,如果您因此通过 ( Model )Form 或ModelAdmin ,或者您将其与File object 一起传递。

Indeed, if you want to save twice an item named 3.jpeg , it will generate:实际上,如果您想保存两次名为3.jpeg的项目,它将生成:

/media/3.jpeg
/media/3_S12ggWF.jpeg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM