What is the way to serialize a user-defined class?

廉价感情. 提交于 2019-12-25 02:19:42

问题


What should a user-defined class implements if I want to serialize it? For my case, I want to serialize a list named

comment_with_vote = []

elements of which are objects defined as follows.

class CommentWithVote(object):
    def __init__(self, comment, vote):
        self.comment = comment
        self.vote = vote # vote=1 is_up,vote=0 is_down,vote=2 no vote

comment is a django model.

serializers.serialize('json', comment_with_vote, ensure_ascii=False)

returns AttributeError: 'CommentWithVote' object has no attribute '_meta'

json.dumps(comment_with_vote, ensure_ascii=False)

returns TypeError: <...CommentWithVote object at 0x046ED930> is not JSON serializable


回答1:


serializers.serialize is only for Django models, and your class isn't a model - it just contains a reference to one. And, unfortunately, json.dumps doesn't know about models or your container class.

I would approach this in a different way. Rather than having a separate CommentWithVote class, I would simply annotate the votes onto the standard Comment. The serializers still won't know about the vote attribute, as it's not a field, but you can do this: serialize to a standard Python dictionary, add the vote, then convert to JSON.

comment_list = serializers.serialize('python', comments)
for comment in comments:
    comment['fields']['vote'] = calculate_vote()
comment_json = json.dumps(comments)


来源:https://stackoverflow.com/questions/7309600/what-is-the-way-to-serialize-a-user-defined-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!