David Foie Gras
David Foie Gras

Reputation: 2080

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.

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.

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.

But I cant be sure of it.

Upvotes: 1

Views: 207

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477309

Case 1: I want to find users that user_john and user_mark are both following.

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 following user_mark.

User.objects.filter(fuser__follow=user_john, ffollow__user=user_mark)

Upvotes: 5

Related Questions