1

I am trying to access the url of an ImageField on a model related through a reverse-ForeignKey. I have attempted various possible options based on examples in the docs, but have had no luck. Any help would be appreciated.


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 (attempt)

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

    class Meta:
        mode = Car

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

exception

'SortedDictWithMetadata' object has no attribute 'default_image'

snakesNbronies
  • 3,619
  • 9
  • 44
  • 73

1 Answers1

0

The new DRF 2.3 seems to be helpful with reverse relationships and has solved my issues.

DRF 2.3 Announcement

For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.

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

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

As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.

class BlogSerializer(serializers.ModelSerializer):
   """Don't need to specify the 'comments' field explicitly anymore."""
   class Meta:
        model = Blog
        fields = ('id', 'title', 'created', 'comments')
Micah Walter
  • 908
  • 9
  • 19
snakesNbronies
  • 3,619
  • 9
  • 44
  • 73