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.following
is still querying onUser
, thus you need to span relation w/__
toFollow
here.The two fields here,
from_user
andto_user
, are bothForeignKey
pointing toUser
model. Thus for anUser()
instanceu
:u.following
searches for theUser()
s who have relationship w/u
through the intermediate table, theFollow
. The key here is thatu.following
picks the firstForeignKey
in theFollow
that points to theUser
, as the reference tou
itself. Thus for your version ofFollow
,u.following.filter(to_user__status=1)
filters on theFollow
items havingfrom_user
equals tou
andto_user
w/status
equals to1
. The lookup is typical following relationship backwardsu.from_user
searches the intermediate table for those havingfrom_user
equals tou
u.to_user
searches the intermediate table for those havingto_user
equals tou
Also, you could filter on the
ForeignKey
directly, w/ remembering that thefrom_user
andto_user
are both ref theFollow
:Seems that
does the trick. Can someone explain to me why, and how this works?
user.following
is a ManyRelatedManager which is querying on User. What woulduser.following.filter(from_user__status=1)
do? Can't to guess what it returns... Thanks again !