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 attribut开发者_如何学Goe '_meta'
json.dumps(comment_with_vote, ensure_ascii=False)
returns TypeError: <...CommentWithVote object at 0x046ED930> is not JSON serializable
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)
精彩评论