我有以下模型定义:
class Photo(models.Model) :
def get_gallery_path(self, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'static/uploads/images/gallery/' + filename
uploader = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(default=date.today)
image = ProcessedImageField(default='', verbose_name='Image', upload_to=get_gallery_path, processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60})
caption = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return str(self.id) + str(self.uploader.username) + str(self.date)
class Meta:
verbose_name_plural = "Photos"
verbose_name = "Photo"
我已经使用django-imagekit修改了上传的图像。但是如您所见,我必须在image
字段中内联声明所有属性和选项。当我指定许多属性时,这使得代码难以阅读。
是否可以在models.py
文件中分别定义属性和选项,以便可以将其用于所有图像字段。
答案 0 :(得分:1)
您可以简单地利用字典解压缩功能。
例如,定义您的字典processed_image_field_specs
:
def get_gallery_path(filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'static/uploads/images/gallery/' + filename
processed_image_field_specs = {
'default': '',
'verbose_name': 'Image',
'upload_to': get_gallery_path,
'processors': [ResizeToFill(100, 50)],
'format': 'JPEG',
'options': {'quality': 60}
}
现在解压缩字典,以为ProcessedImageField
提供命名参数:
class Photo(models.Model) :
...
image = ProcessedImageField(**processed_image_field_specs)
...