Reputation: 349
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
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 User
s 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 aManyToManyField
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