ParsaAi
ParsaAi

Reputation: 349

How to get objects which have an object in their ManyToManyField?

There's this model:

class User(AbstractUser):
    followers = models.ManyToManyField('self', symmetrical=False, related_name='followings', null=True, blank=True)

Say I have a user object called 'A'. In a view, I want to filter User objects which have 'A' as their follower. How can I do that?

Upvotes: 1

Views: 758

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

You can query with:

A.followings.all()

The related_name=… [Django-doc] is the name of the relation in reverse, so it is a QuerySet of Users that have A as follower.

If you do not specify a related_name=… it will take the name of the model in lowercase followed by the …_set suffix, so user_set in this case.

If you only have the primary key of A, then you can query with:

User.objects.filter(followers__id=a_id)

Note: Using null=True [Django-doc] for a ManyToManyField [Django-doc] makes no sense: one can not enforce by the database that a ManyToManyField should be non-empty, therefore as the documentation says: "null has no effect since there is no way to require a relationship at the database level."

Upvotes: 2

Related Questions