[Answer]-Django inner join on self. Is there a more efficient approach?

1👍

I’m not totally sure what you are trying to achieve, but if I’m getting it right you want all users for which Follow object exists where request.use is the follower and one where request.user is followed (I think the related_names are a bit confusing).

In you source code you use anUserProfile and a User model, not sure if that’s a typo or intentional, but assuming there’s just the User model this might work:

user = request.user
users = User.objects.filter(
    Q(Q(follower__follower=user) & Q(following__following=user)) |
    Q(pk=user.pk))).distinct()

Leave a comment