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

1K
Views
How can I access to data stored in a ManyToMany related table in Django?

I want to make a query to obtain all the users that another user is "following" for a learning project.

When I execute the following python code:

user = User.objects.get(id=user_id)
followers = user.follows.all()

I don't get an error but instead I get a list with an object ( called Follow object (4) ) from which I can't access the user related properties.

I've checked this documentation here: https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/

But I can't find where I'm failing to use properly this type of model-relation.

Here are my Django models:

class User(AbstractUser):
    pass

class Follow(models.Model):
    user = models.ForeignKey(User, null=False, on_delete=models.CASCADE, related_name="follows")
    follow = models.ManyToManyField(User, blank=True, related_name="followed_by")

I searched in my Django DB to see what is happening and I saw that there is a relational table called "network_follow_follow" that in fact has all the info that I need and is related with the object that I get from my Query, here are two pictures about the table that I can access and the one that I don't know how to access: Table data requested by my code:
Table data requested by my code

Table that I need to query:
Table that I need to query

So now I'm looking a way to access that last table, but to know how can I access straight forward to the last table data would be much better I think.

Thanks in advance.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

See if this works for you.

follow_object = Follow.objects.filter(user=user)
followers_of_user = follow_object.follow.all()

I think the problem is that the user object does not have a user.follows function. You have created a seperate table in the database with that relationship data. I'm sure there's a better way of doing it but that's what I have done with something similar in my project.

over 4 years ago · Santiago Trujillo 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!