I have the following – simplified – models:
class User(models.Model):
following = models.ManyToManyField("self", through='Following', symmetrical=False)
class Following(models.Model):
from_user = models.ForeignKey(User, related_name='from_user')
to_user = models.ForeignKey(User, related_name='to_user')
status = models.IntegerField()
The status is 0 for pending, 1 for following
Let user be a User. I would like to get all the followed users of user
I can do
user.following.all()
to get all the users user is following (pending relationships OR really follow)
or
Following.objects.filter(from_user=user, status=1)
to get all the Following objects with User user and real friendship
But how can I get all the User objects for user and status=1 ?
I can’t seem to find a way
Thank you !
Try
the
user.followingis still querying onUser, thus you need to span relation w/__toFollowhere.The two fields here,
from_userandto_user, are bothForeignKeypointing toUsermodel. Thus for anUser()instanceu:u.followingsearches for theUser()s who have relationship w/uthrough the intermediate table, theFollow. The key here is thatu.followingpicks the firstForeignKeyin theFollowthat points to theUser, as the reference touitself. Thus for your version ofFollow,u.following.filter(to_user__status=1)filters on theFollowitems havingfrom_userequals touandto_userw/statusequals to1. The lookup is typical following relationship backwardsu.from_usersearches the intermediate table for those havingfrom_userequals touu.to_usersearches the intermediate table for those havingto_userequals touAlso, you could filter on the
ForeignKeydirectly, w/ remembering that thefrom_userandto_userare both ref theFollow: