dan_boy
dan_boy

Reputation: 2009

How to JSON serialize objects that contain a file?

I want to retrieve Story together with the associated story_media from my DRF backend. Story_Media contains both data and files and comes as a list. This means a single Story can have multiple Story_Media objects (Story is FK in story_media).

However, when I want to return the litst of Story_Media objects, it seems that they are not serializable. So my question is, how do I JSON serialize objects that contain a file?

TypeError: Object of type Story_Media is not JSON serializable

class StoryRetrieveSerializer (serializers.ModelSerializer):
    story_media = serializers.SerializerMethodField('get_story_media')

    class Meta:
        model = Story
        fields =  ('title', 'story_media')

    def get_story_media(self, story):
        return Story_Media.objects.filter(story=story.id)

Upvotes: 0

Views: 149

Answers (1)

Mahmoud Adel
Mahmoud Adel

Reputation: 1330

You need to create a serializer for Story_Media, pass the objects of your queryset to it with many=True and return serializer data

For ex:

def get_story_media(self, story):
        qs = Story_Media.objects.filter(story=story.id)
        serializer = StoryMediaSerializer(qs, many=True)
        return serializer.data

Upvotes: 2

Related Questions