序列化用户定义的类的方法是什么?

时间:2011-09-05 14:43:27

标签: django serialization

如果我要序列化,用户定义的类应该实现什么?对于我的情况,我想序列化一个名为

的列表
comment_with_vote = []

其元素是如下定义的对象。

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

评论是一个django模型。

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

返回AttributeError:'CommentWithVote'对象没有属性'_meta'

json.dumps(comment_with_vote, ensure_ascii=False)

返回TypeError:< ... CommentVithVote对象位于0x046ED930>不是JSON可序列化的

1 个答案:

答案 0 :(得分:0)

serializers.serialize仅适用于Django模型,而您的类不是模型 - 它只包含对一个模型的引用。不幸的是,json.dumps不了解模型或容器类。

我会以不同的方式处理这个问题。我没有单独的CommentWithVote类,而只是将注释注释到标准Comment上。序列化程序仍然不知道投票属性,因为它不是字段,但您可以这样做:序列化为标准Python字典,添加投票,然后转换为JSON。

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