Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 852
Tom Finet Avatar asked Jan 25 '26 15:01

Tom Finet


1 Answers

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.

like image 94
Peter DeGlopper Avatar answered Jan 27 '26 06:01

Peter DeGlopper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!