Serializing a list of objects with django-rest-framework

DjangoDjango Rest-Framework

Django Problem Overview


In DRF, I can serialize a native Python object like this:

class Comment(object):
    def __init__(self, email, content, created=None):
        self.email = email
        self.content = content
        self.created = created or datetime.now()

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

comment = Comment(email='[email protected]', content='foo bar')
serializer = CommentSerializer(comment)
serializer.data

# --> {'email': '[email protected]', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}

Is it possible to do the same for a list of objects using ListSerializer?

Django Solutions


Solution 1 - Django

You can simply add many=True for serialising list.

comments = [Comment(email='[email protected]', content='foo bar'),
            Comment(email='[email protected]', content='foo bar 1'),
            Comment(email='[email protected]', content='foo bar 2')]
serializer = CommentSerializer(comments, many=True)
serializer.data

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbavazaView Question on Stackoverflow
Solution 1 - DjangoBipul JainView Answer on Stackoverflow