Django模型重写save方法仅单个图片缩放生效的问题排查
问题
在UserProfile模型中定义了profile_picture和cover_photo两个ImageField字段,编写了两个save方法分别对上传图片做缩放处理,但目前仅最后定义的方法生效;交换方法顺序后,则仅另一个方法生效。请问问题原因是什么?如何让两个图片缩放逻辑都正常工作?
相关代码
class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) profile_picture = models.ImageField(upload_to='users/profile_pictures', blank=True, null=True) cover_photo = models.ImageField(upload_to='users/cover_photos', blank=True, null=True) ... def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.profile_picture: img = Image.open(self.profile_picture.path) if img.height > 50 or img.width > 50: new_height = 100 new_width = int(new_height / img.height * img.width) img = img.resize((new_width, new_height)) img.save(self.profile_picture.path) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.cover_photo: img = Image.open(self.cover_photo.path) if img.width > 100 or img.height > 100: new_width = 600 new_height = int(new_width / img.width * img.width) img = img.resize((new_height, new_width)) img.save(self.cover_photo.path)
问题原因
在Python类中,后定义的同名方法会直接覆盖之前的方法。你在UserProfile里写了两个同名的save方法,第二个方法会完全替换第一个,所以不管怎么调整顺序,永远只有最后那个save方法会被执行,另一个的逻辑根本不会运行。
解决方法
把两个图片的缩放逻辑合并到同一个save方法里,这样调用save()时会依次执行两个处理逻辑。同时修正原代码中封面图缩放的计算错误(原代码会导致图片比例失真),修改后的代码如下:
from PIL import Image from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) profile_picture = models.ImageField(upload_to='users/profile_pictures', blank=True, null=True) cover_photo = models.ImageField(upload_to='users/cover_photos', blank=True, null=True) # 其他字段... def save(self, *args, **kwargs): super().save(*args, **kwargs) # 处理头像缩放 if self.profile_picture: img = Image.open(self.profile_picture.path) if img.height > 50 or img.width > 50: new_height = 100 new_width = int(new_height / img.height * img.width) img = img.resize((new_width, new_height)) img.save(self.profile_picture.path) # 处理封面图缩放 if self.cover_photo: img = Image.open(self.cover_photo.path) if img.width > 100 or img.height > 100: new_width = 600 # 按原图片比例计算新高度,避免失真 new_height = int(new_width / img.width * img.height) img = img.resize((new_width, new_height)) img.save(self.cover_photo.path)
内容的提问来源于stack exchange,提问作者RMCode
相关产品推荐
相关产品推荐

