Django Rest Framework - 反向外键上的图像网址

时间:2013-05-03 06:53:06

标签: django django-rest-framework

我正在尝试通过反向访问相关模型ImageField的网址 - ForeignKey。我已根据文档中的示例尝试了各种可能的选项,但没有运气。任何帮助,将不胜感激。


models.py

class Car(models.Model):
    name = models.CharField(... )

    @property
        def default_image(self):
            ... ...
            return image # <=== returns from the CarImage model

class CarImage(models.Model):
    car = models.ForeignKey(Car) # <=== no related_name set, but technically we could use carimage_set
    image = models.ImageField(... ...)

serializers.py(尝试)

class CarSerializer(serializers.ModelSerializer):
    ... ...
    image = fields.SerializerMethodField('get_image')

    class Meta:
        mode = Car

    def get_image(self, obj):
        return '%s' % obj.default_image.url

的异常

'SortedDictWithMetadata' object has no attribute 'default_image'

1 个答案:

答案 0 :(得分:0)

新的DRF 2.3似乎对反向关系有所帮助,并解决了我的问题。

DRF 2.3 Announcement

例如,在REST框架2.2中,反向关系需要显式包含在序列化程序类中。

类BlogSerializer(serializers.ModelSerializer):     comments = serializers.PrimaryKeyRelatedField(many = True)

class Meta:
    model = Blog
    fields = ('id', 'title', 'created', 'comments')

从2.3开始,您可以只包含字段名称,相应的序列化字段将自动用于关系。

class BlogSerializer(serializers.ModelSerializer):
   """Don't need to specify the 'comments' field explicitly anymore."""
   class Meta:
        model = Blog
        fields = ('id', 'title', 'created', 'comments')