Skip to content
Advertisement

Django: How do I get referenced objects in a symmetric ManyToMany relationship?

I’ve created a Many-to-Many relationship for the model UserProfile, to enable users to grant access to a particular feature to one another. The relationship works as expected with the use of symmetrical=False to ensure a user access is one-way.

Model

JavaScript

I am able to query the users that a particular user wants to grant access to via: (for example id=1)

JavaScript

However, I would like to retrieve the users that have granted access to the particular user.

How would I do this?

Additional Information

Using Relation Database Information

Advertisement

Answer

You can filter with:

JavaScript

With your sample data, it will return the UserProfile with id=7 for this query.

or if you want to query in reverse:

JavaScript

With your sample data, it will return the UserProfiles with id=7, id=3, user=4 and user=7 for this query.

Advertisement