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 ?
You should define a source of related model instances and set many=True
:
images = ProductImageSerializer(many=True, source='images.all')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With