Skip to content
Advertisement

How to serialize a model with many to maany relashionship?

I have this function in my model,

    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()),
        }

but likes is actualy a many to many relashionship with User. How can I serialize it to get something like this?

    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.
               ],
        }

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.

 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()),
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement