Tom Finet
Tom Finet

Reputation: 2136

Excluding a list of a user's friends from the User.objects.all() queryset in django

In one of my views I override the get_queryset(self) method in order to return a list of users that excludes the friends of the user making the request and the same user. This is what my code looks like:

def get_queryset(self):
    all_users = User.objects.all()
    user_friends = Friend.objects.friends(self.request.user)
    # Filter all_users to exclude all elements of the user_friends queryset.
    # Filter all_users to exclude the current user making the request.
    # Return the filtered queryset.

I am using the django-friendship library to handle friend requests and users being friends. In the getting data about friendship section, it says to get a list of all a user's friends all that needs to be done is Friend.objects.friends(request.user). I am unsure if this would return a list of Friend instances or of User instances. The source code for the Friend model is here. In either case, how would I filter the queryset all_users to exclude all elements of the list user_friends.

Upvotes: 3

Views: 3856

Answers (2)

Javed Gouri
Javed Gouri

Reputation: 359

users = UserRoleAccount.objects.filter(groups__in = ura_groups).distinct().exclude(id=ura.id)

Upvotes: 0

Peter DeGlopper
Peter DeGlopper

Reputation: 37344

It looks like the library enforces that friendships are reciprocal, so you should be able to exclude people who are friends of the user with just User.objects.exclude(friends__from_user=self.request.user). Or all_user.exclude(friends__from_user=self.request.user) if you prefer.

To exclude the user as well, add a .exclude(id=self.request.user.id). It doesn't matter whether that's before or after the friends exclude call.

Friend.objects.friends(request.user) returns a list of users, as you can see from inspecting its source: https://github.com/revsys/django-friendship/blob/ef711250a85b8d2d59af8bb7b61d088d3aea57e8/friendship/models.py#L154

The line friends = [u.from_user for u in qs] converts from a queryset of Friend instances into a list of users.

Upvotes: 1

Related Questions