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
?
To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.
It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With