3
votes

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.

2
Friends have to_user and from_user attributes. When you say you want to filter the all_users QuerySet, should that be based on the to_user or the from_user values in user_friends?Chris
It should be based on the attribute that gives that the user's friends. So isn't that to_user?Tom Finet

2 Answers

1
votes

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.

0
votes

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