How to get objects which have an object in their ManyToMany field?
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?
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 aManyToManyField[Django-doc] makes no sense: one can not enforce by the database that aManyToManyFieldshould be non-empty, therefore as the documentation says: "nullhas no effect since there is no way to require a relationship at the database level."