67

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?

1 Answer 1

127

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
Sign up to request clarification or add additional context in comments.

4 Comments

And how to un-serialize a list?
many=True is what I was looking for over an hour
List serializer not validating the object, if I remove many=True and run an empty single object it gets validated for required fields. for the list, it is always 200 for an empty list.
I was missing many=True again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.