例如,如果我想从文件系统和数据库行中删除所有上传的图像,那么有这样的模型实例:
class PictureSet(models.Model):
image1 = models.ImageFIeld(upload_to="images/")
image2 = models.ImageFIeld(upload_to="images/")
image3 = models.ImageFIeld(upload_to="images/")
我有更短的可能性吗? [实例]:
picture_set1 = PictureSet.objects.get(id=1)
picture_set1.image1.delete()
picture_set1.image2.delete()
picture_set1.image3.delete()
picture_set1.delete()
???
答案 0 :(得分:2)
我建议覆盖模型的删除方法:
def delete(self, *args, **kwargs):
for field in self._meta.fields:
if type(field) == models.ImageField:
image = self.__getattribute__(field.name)
image.delete()
super(self.__class__, self).delete(*args, **kwargs)
然后只是:
PictureSet.objects.get(id=1).delete()
答案 1 :(得分:0)
picture_set = PictureSet.objects.get(id=1)
picture_set1.delete()
删除整个图片集类,不需要删除所有内容......
如果图片本身停留在那里,只需执行某种清理功能,检查上传文件夹和存储在数据库中的图像链接
希望这会有所帮助