Include nested element in Django Rest environment serializer

I am trying to list all images of one element in a Django rest Framework serializer.

In models:

class Item(TimeStampedModel, AbsoluteUrlMixin, ObjectReviewsMixin):
   ...

class ItemImage(models.Model):
    item = models.ForeignKey(Item, related_name='pictures')
    picture = models.ImageField(null=True, blank=True, upload_to="items")

      

in view:

class ItemImageViewSet(viewsets.ModelViewSet):
    queryset = ItemImage.objects.all()
    serializer_class = ItemSerializer()

      

in serializer:

class ItemImageSerializer(serializers.Serializer):
    class Meta:
        model = ItemImage
        fields =(
            'picture'
        )


class ItemSerializer(ObjectReviewsSerializer):
    pictures = ItemImageSerializer()
    ...

      

When I got to /items/1

I have an empty answer for field images For example "pictures":{}

While it should return a list of images.

+3


source to share


1 answer


You include the field pictures

in ImageSerializer

, but you are not using the Django REST framework to accept multiple values.

You must pass many=True

in the field when initializing it

class ItemImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemImage
        fields =(
            'picture',
        )


class ItemSerializer(ObjectReviewsSerializer):
    pictures = ItemImageSerializer(many=True)
    ...

      



And the reason it didn't throw an error is because you were missing the comma after 'picture'

in the tuple. It is highly recommended to always include a trailing comma, otherwise single-entry tuples will be separated. So your margins were indeed ('p', 'i', 'c', 't', 'u', 'r', 'e', )

, which is clearly not what you want.

Another reason is that you used Serializer

as a ModelSerializer

, so no fields were actually created. The Django REST framework ignores any included fields that Meta.fields

are not actually defined, so you always get an empty object.

I have included the comma in the modified code and also changed your serializer to ModelSerializer

.

+2


source







All Articles