本文介绍了使用Django-rest-framework序列化对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在中,我可以序列化本机像这样的Python对象:

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?

推荐答案

您只需添加many = True即可序列化列表。

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

这篇关于使用Django-rest-framework序列化对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 06:33