Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a list of objects with django-rest-framework

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?

like image 783
bavaza Avatar asked Feb 22 '17 17:02

bavaza


People also ask

How do you serialize a list of objects in Django REST framework?

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.

What is serialization in Django REST framework?

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.

Is serialization necessary in Django?

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.


1 Answers

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 
like image 170
Bipul Jain Avatar answered Sep 21 '22 04:09

Bipul Jain