如何序列化模型与许多maany relashionship吗?



我的模型中有这个函数,

def serialize(self):
return {
'id': self.id,
'author': self.author.username,
'text': self.text,
'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"),
'likes': self.likes.all(),
'likes_number': len(self.likes.all()),
}

但是点赞实际上是用户对用户的多对多关系。我怎么序列化它来得到这样的东西呢?

def serialize(self):
return {
'id': self.id,
'author': self.author.username,
'text': self.text,
'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"),
'likes': [
user1,
user2,
etc.
],
}

这样我就可以去掉like number属性了

你可以使用列表推导来序列化你的数据,但是使用django rest框架的序列化器更合适。

return {
'id': self.id,
'author': self.author.username,
'text': self.text,
'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"),
'likes': [{'id':like.id,...} for like self.likes.all()],
'likes_number': len(self.likes.all()),
}

最新更新