我有一个自定义验证器,可以检查上传的图库图像的大小是否太大。
无论字段是否更改,每次保存模型时都会运行此验证器。这通常不会是一个大问题。问题是我有一个内联管理面板,每当我保存父模型“Profile”时,所有子模型“GalleryImages”内部的验证都会被执行。 50 张图像的验证需要很长时间,因为它需要加载所有图像并检查分辨率。
如何配置此验证器仅在字段值已更新时运行?
# models.py
@deconstructible
class ImageValidator(object):
""" Checks that image specs are valid """
def call(self, value):
# Some code to check for max size, width and height
if too_big:
ValidationError('Image is too big')
class Profile(Model):
user = models.ForeignKey(User)
class GalleryImage(Model):
profile = models.ForeignKey(Profile)
image = models.ImageField(validators=[ImageValidator])
# admin.py
class GalleryImageInline(admin.TabularInline):
model = GalleryImage
@admin.register(Profile)
class ProfileAdmin(ModelAdmin):
inlines = [GalleryImage]
使用此功能
def file_size(value):
limit = 2 * 1024 * 1024
if value.size > limit:
raise ValidationError("File too large. Size should not exceed 2 MB.")
在这样的模型中使用它
validators=[file_size]