我有一个用于用户个人资料图像的模型,当我删除具有默认图像的用户时,默认图像也会被删除。我相信这是必须要做的,因为我设置了on_delete = models.CASCADE。
我尝试将on_delete = PROTECT放在ImageField中,但是它无法识别该属性。
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300,300)
img.thumbnail(output_size)
img.save(self.image.path)
答案 0 :(得分:0)
on_delete=models.PROTECT
是models.ForeignKey
的自变量,其目的是用于关系。
在这种情况下,您需要通过扩展ImageField
class的类型并使用所需的功能覆盖原始类delete
的方法来创建自己的{{3}}类型。