Serializing a list of objects using django-rest-framework

In DRF , I can serialize my own Python object as follows:

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=' leila@example.com ', content='foo bar') serializer = CommentSerializer(comment) serializer.data # --> {'email': ' leila@example.com ', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'} 

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

+7
django django-rest-framework
source share
1 answer

You can simply add many = True to serialize the list.

 comment = [Comment(email=' leila@example.com ', content='foo bar'),Comment(email=' leila1@example.com ', content='foo bar 1'),Comment(email=' leila2@example.com ', content='foo bar 2')] serializer = CommentSerializer(comment, many=True) serializer.data 
+17
source share

All Articles