django-imagekit获取模型属性

时间:2015-01-12 08:21:27

标签: django django-models django-imagekit

我有以下型号:

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

和自定义Watermark类:

class Watermark(object):    

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

如何从Watermark类中访问我的模型属性“property”?

谢谢

1 个答案:

答案 0 :(得分:1)

您需要创建一个自定义规范,从模型中获取所需信息并将其传递给处理器。文档显示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)注册它,如上所示