Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the values of a related model in Django Rest Framework?

I want get all the images of a product in the serialized form. My models are as below.

class Product():
    title 
    subtitle 
    ...
class ProductImage():
    product = models.ForeignKey(
    'Product', related_name='images', verbose_name=_("Product"))
    image_path

My serializers :

class ProductImageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ProductImage
        fields = ('caption', 'display_order', 'original', 'product')


class ProductSerializer(serializers.HyperlinkedModelSerializer):

    images = ProductImageSerializer()
    class Meta:
        model = Product
        fields = (
            'title', 'slug', 'short_description', 'description',
            'sku', 'pk', 'images')

I am getting this error

AttributeError at /api/products/ Got AttributeError when attempting to get a value for field `display_order` on serializer `ProductImageSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'display_order'.

How do I get all the images for a particular product ?

like image 661
Coderaemon Avatar asked Dec 21 '15 11:12

Coderaemon


1 Answers

You should define a source of related model instances and set many=True:

images = ProductImageSerializer(many=True, source='images.all')
like image 62
Igor Pomaranskiy Avatar answered Oct 31 '22 23:10

Igor Pomaranskiy