我有这样一个类:
class Image (models.Model):
...
sizes = ((90,90), (300,250))
def resize_image(self):
for size in sizes:
...
还有一个这样的类:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image)
我想用那个类做的是:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image, sizes=((90,90), (150, 120)))
我可以在这里指定我希望 Image 类用来调整自身大小的大小作为参数,而不是在类上进行硬编码。我意识到我可以在调用 resize_image 时传递这些,如果它是直接调用的,但我的想法是当对象持久化到数据库时自动调用 resize_image 方法。
如果我尝试像这样通过外键声明传递参数,我会立即收到错误消息。在我开始深入研究 Django 之前,有没有一种简单/更好的方法可以做到这一点?
请您参考如下方法:
您可能正在插入它上坡;尝试将参数应用于 FK 并不常见。
针对您的具体情况的常规解决方案是使用缩略图(如“sorl”)在交付前立即进行缩略图替换 - 即:在模板中,例如:
{% thumbnail myobj.image 500 500 %}
尽管我个人已将例程添加到我的类(class)中,以便更轻松地访问这些缩略图。例如:
def thumbnail(self):
path = # work out the path to the thumbnail
try:
#access the path where I expect the thumbnail file to be
except #failure:
# generate the thumbnail using the dimensions specified by the class
return #path to the thumbnail
