django-imagekit 获取模型属性

django-imagekit get model attribute

我有以下型号:

class PropertyPhoto(models.Model):
    property = models.ForeignKey('Property')
    photo_show = ProcessedImageField(upload_to=get_web_watermark,
                                  processors=[Watermark()],                                     
                                  options={'quality': 95})

和自定义水印class:

class Watermark(object):    

    def process(self, image):
        try:
            this_property = Property.objects.get(pk=*self.property.id*)
        except Property.DoesNotExist:
            print "error"

如何从 Watermark class 内部访问我的模型属性 "property"?

谢谢

您需要创建一个自定义规范,从模型中获取您需要的信息并将其传递给您的处理器。文档显示 an example:

from django.db import models
from imagekit import ImageSpec, register
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
from imagekit.utils import get_field_info

class AvatarThumbnail(ImageSpec):
    format = 'JPEG'
    options = {'quality': 60}

    @property
    def processors(self):
        model, field_name = get_field_info(self.source)
        return [ResizeToFill(model.thumbnail_width, thumbnail.avatar_height)]

register.generator('myapp:profile:avatar_thumbnail', AvatarThumbnail)

class Profile(models.Model):
    avatar = models.ImageField(upload_to='avatars')
    avatar_thumbnail = ImageSpecField(source='avatar',
                                      id='myapp:profile:avatar_thumbnail')
    thumbnail_width = models.PositiveIntegerField()
    thumbnail_height = models.PositiveIntegerField()

请注意,您可以将规范直接传递给 ImageSpecField 构造函数(使用 spec kwarg)而不是使用 id 注册它(并使用 id kwarg)作为如上所示。