Home > database >  How to serialize a model with many to maany relashionship?
How to serialize a model with many to maany relashionship?

Time:07-07

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.

CodePudding user response:

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