具有动态属性的Django模型 [英] Django Model with dynamic attributes

查看:80
本文介绍了具有动态属性的Django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全不熟悉编程,所以请原谅可能是一个愚蠢的问题,但是过去几天来我一直在努力思考。

I'm totally, completely new to programming, so please forgive what is probably a stupid question, but I've been beating my head on this for the past couple of days.

我有两个模型,照片和缩略图。我正在尝试一种简单,动态的方法来获取每张照片的缩略图链接。我已经提出了一个执行此操作的函数(get_thumbs),但是我希望它在调用模型时自动运行(基本上是这样,只要模型可用,我就会立即获得Photo.get_%s_url%thumb.name)

I have two models, Photos and Thumbnails. I'm trying to come up with an easy, dynamic way to get the thumbnail links for each Photo. I've come up a function that does this (get_thumbs) but I'd like it to run automatically when the model is called (basically so that I get Photo.get_%s_url % thumb.name as soon as the model is available).

下面是我的models.py。朝着正确方向(即使只是 google blah)的任何帮助或微调将不胜感激。

Below is my models.py. Any help or nudge in the right direction (even if it's just "google blah") would be greatly appreciated. Thanks.

class Photo(models.Model):
    name = models.CharField(max_length=100)
    original_image = models.ImageField(upload_to='photos')
    caption = models.TextField(null=True, blank=True)
    title_slug = models.SlugField(null=True, blank=True, unique=True)
    rootfilename = models.CharField(max_length=50, editable=False, blank=True)
    num_views = models.PositiveIntegerField(editable=False, default=0)

    def __unicode__(self):
        return self.name

    thumbnails = Thumbnail.objects.all()

    def create_thumbs(self):
        for thumbnail in self.thumbnails:
            fname = (settings.MEDIA_ROOT + self.rootfilename + '_' + thumbnail.name + '.jpg')
            if exists(fname):
                None
            else:
                t_img = Image.open(self.original_image.path)
                t_fit = ImageOps.fit(t_img, (thumbnail.height,thumbnail.width), Image.ANTIALIAS, 0, (0.5,0.5))
                t_fit.save(fname,"JPEG")

    def save(self, *args, **kwargs):
        self.rootfilename = (self.original_image.name).strip('photos/.jpg')
        super(Photo, self).save(*args, **kwargs)
        self.create_thumbs()

    def get_thumbs(self):
        for thumb in self.thumbnails:
            setattr(self, ('get_'+thumb.name+'_url'), ('thumbs/'+self.rootfilename+'_'+thumb.name+'.jpg'))


推荐答案

您要像使用save方法一样覆盖 __ init __ 方法,并调用 self .get_thumbs(),然后再调用super(照片,自我)。初始化(* args,** kwargs)

You want to override the __init__ method like you did with the save method, and call self.get_thumbs() before you call super(Photo, self).init(*args, **kwargs)

或者,您可以看看其他人对这个问题的解决方案sorl.thumbnail,django-imagekit或easy-thumbnails(有点像两者的结合)

Alternately, you could look at other peoples solution to this problem sorl.thumbnail, django-imagekit, or easy-thumbnails (which is sort of like a combination of the two)

这篇关于具有动态属性的Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆