Home > Mobile >  How can I access to data stored in a ManyToMany related table in Django?
How can I access to data stored in a ManyToMany related table in Django?

Time:11-02

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: 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.

CodePudding user response:

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.

  • Related