Django不对称自我通过关系查询 [英] Django asymettrical self through relationship query

查看:97
本文介绍了Django不对称自我通过关系查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简化模型:

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 the User()s who have relationship w/ u through the intermediate table, the Follow. The key here is that u.following picks the first ForeignKey in the Follow that points to the User, as the reference to u itself. Thus for your version of Follow, u.following.filter(to_user__status=1) filters on the Follow items having from_user equals to u and to_user w/ status equals to 1. The lookup is typical following relationship backwards
  • u.from_user searches the intermediate table for those having from_user equals to u
  • u.to_user searches the intermediate table for those having to_user equals to u

另外,您可以直接过滤 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆