Django不对称自我通过关系查询 [英] Django asymettrical self through relationship query
问题描述
我有以下简化模型:
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()
状态为0,待处理为1,以下为
让用户成为用户。我想获得用户的所有追踪用户
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
我可以做
user.following.all()
获取用户所关注的所有用户(待处理关系或者真的跟着)
to get all the users user is following (pending relationships OR really follow)
或
Following.objects.filter(from_user=user, status=1)
获取用户用户和真实友谊的所有关注对象
to get all the Following objects with User user and real friendship
但是如何获取user和status = 1的所有User对象?
我似乎找不到一种方式
But how can I get all the User objects for user and status=1 ? I can't seem to find a way
谢谢!
推荐答案
尝试
user.following.filter(to_user__status=1)
user.following
仍在查询 code>,因此您需要将关系w /
__
到跟随
在这里。
这两个字段 from_user
和 to_user
都是 ForeignKey
指向用户
模型。因此,对于 User()
实例 u
:
The two fields here, from_user
and to_user
, are both ForeignKey
pointing to User
model. Thus for an User()
instance u
:
-
u.following
搜索User()
s谁有关系w /u
通过中间表,跟随
。关键在于u.following
在跟随$中选择第一个
ForeignKey
c $ c>指向用户
,作为u
本身的引用。因此,对于您的版本跟随
,u.following.filter(to_user__status = 1)
过滤器关注
具有from_user
的项目等于u
和to_user
w /status
等于1
。查找是典型的以下关系向后 -
u.from_user
在中间表中搜索具有from_user
等于u
-
u.to_user
在中间表中搜索具有to_user
等于u
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
另外,您可以直接过滤 ForeignKey
,记住 from_user
和 to_user
都是参考跟随
:
Also, you could filter on the ForeignKey
directly, w/ remembering that the from_user
and to_user
are both ref the Follow
:
User.objects.filter(to_user__from_user=user, to_user__status=1) # user as from_user
User.objects.filter(from_user__to_user=user, from_user__status=1) # user as to_user
User.objects.filter(following=user) # those who are followed by `to_user` user
这篇关于Django不对称自我通过关系查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!