Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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()),
    }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!