1

我有以下模型:

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

和自定义水印类:

class Watermark(object):    

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

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

谢谢

4

1 回答 1

2

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

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构造函数(使用speckwarg),而不是使用 id 注册它(并使用idkwarg),如上所示。

于 2015-01-13T04:20:37.797 回答