覆盖django中的FieldFile对象

问题描述:

如何以最小的痛苦将自定义属性或方法添加到ImageFieldFile对象?覆盖django中的FieldFile对象

比如我有这样的模式:

class SomeModelWithImage(models.Model): 
    image = models.ImageField() 

和类:

class Custom(object): 

    def __repr__(self): 
     return "<Custom object>"  

我想以某种方式覆盖ImageFieldFile对象,因此它必须返回我的自定义对象的计算方法,如:

>> from models import SomeModelWithImage 
>> i = SomeModelWithImage.objects.all()[0] 
>> i.image 
    <ImageFieldFile: /path/to/file> 
>> i.image.custom_text 
    <Custom object> 

UPD。我改变了一些对象名称,使问题变得抽象并且不会让你感到困惑

在Django中,一个模型字段总是对应一个数据库列,所以你想要的是不可能的。此外,你的类名应该总是单数,因为类'Image'的对象应该是单个图像。我想你可能想要更多的东西像下面这样:

class ImageSet(models.Model): 
    images = models.ManyToManyField('Image') 

class Image(models.Model): 
    image_file = models.ImageField() 
    custom_text = models.CharField(max_length=255) 

编辑:

如果你想计算字段/方法,并不需要额外的数据库信息,只要继承models.ImageField:

class MyImageField(models.ImageField): 
    my_class_attr = "BLARG" 

    def my_method(self): 
     print self.my_class_attr