Django Rest Framework - image url on reverse foreignkey -


i trying access url of imagefield on model related through reverse-foreignkey. have attempted various possible options based on examples in docs, have had no luck. appreciated.


models.py

class car(models.model):     name = models.charfield(... )      @property         def default_image(self):             ... ...             return image # <=== returns carimage model  class carimage(models.model):     car = models.foreignkey(car) # <=== no related_name set, technically 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'

the new drf 2.3 seems helpful reverse relationships , has solved issues.

drf 2.3 announcement

for example, in rest framework 2.2, reverse relationships needed included explicitly on serializer class.

class blogserializer(serializers.modelserializer): comments = serializers.primarykeyrelatedfield(many=true)

class meta:     model = blog     fields = ('id', 'title', 'created', 'comments') 

as of 2.3, can include field name, , appropriate serializer field automatically used relationship.

class blogserializer(serializers.modelserializer):    """don't need specify 'comments' field explicitly anymore."""    class meta:         model = blog         fields = ('id', 'title', 'created', 'comments') 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -