I have this function in my model,
JavaScript
x
10
10
1
def serialize(self):
2
return {
3
'id': self.id,
4
'author': self.author.username,
5
'text': self.text,
6
'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"),
7
'likes': self.likes.all(),
8
'likes_number': len(self.likes.all()),
9
}
10
but likes is actualy a many to many relashionship with User. How can I serialize it to get something like this?
JavaScript
1
13
13
1
def serialize(self):
2
return {
3
'id': self.id,
4
'author': self.author.username,
5
'text': self.text,
6
'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"),
7
'likes': [
8
user1,
9
user2,
10
etc.
11
],
12
}
13
So that I can also get rid of the ‘likes number’ property.
Advertisement
Answer
You can use list comprehension to serialize your data, but using django rest framework’s serializer is more proper.
JavaScript
1
9
1
return {
2
'id': self.id,
3
'author': self.author.username,
4
'text': self.text,
5
'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"),
6
'likes': [{'id':like.id, } for like self.likes.all()],
7
'likes_number': len(self.likes.all()),
8
}
9