[英]django How to use Q and filter related_name in this case?
I have a follow model like it:我有一个像这样的跟随模型:
class Follow(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='fuser') #who is following
follow = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ffollow') #who is followed
And then I want to get users by follow.然后我想通过关注来获得用户。
Case1: I want to find users that user_john and user_mark are both following.案例 1:我想找到 user_john 和 user_mark 都在关注的用户。
users = User.objects.filter(Q(this_user_is_followed_by=user_john)
& Q(this_user_is_followed_by=user_mark))
Case2: Want to find users who is followed by user_john, but who is following user_mark.案例2:想找user_john关注的用户,但是关注user_mark的用户。
users = User.objects.filter(Q(there_user_is_followed_by=user_john)
& Q(these_user_are_following=user_mark))
How to do that filter?那个过滤器怎么做? Its too hard.
太难了。
users = User.objects.filter(Q(ffollow__user=user)
& Q(ffollow__user=user_who_read))
will be answer to Case1.将回答 Case1。
But I cant be sure of it.但我不能确定。
Case 1: I want to find users that
user_john
anduser_mark
are both following.案例 1:我想找到
user_john
和user_mark
都在关注的用户。
The first case should be resolved with two filters, since otherwise you are filtering on the same related object:第一种情况应使用两个过滤器解决,否则您将过滤同一个相关对象:
User.objects.filter(
fuser__follow=user_john).filter(
fuser__follow=user_mark)
Case 2: Want to find users who is followed by
user_john
, but who is followinguser_mark
.案例 2:想找到关注
user_john
,但关注user_mark
。
User.objects.filter(
fuser__follow=user_john,
ffollow__user=user_mark)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.