Hiddenguy
Hiddenguy

Reputation: 537

Get values from a specific user - queryset in Django

I stuck with this queryset, no idea how to write it properly. So I'd like to see all related users to this specific user, in other words I have a friend list.

models.py

class Friend(models.Model):
    user = models.ForeignKey(User, related_name="friendship_creator_set", on_delete=models.CASCADE)
    friend = models.ForeignKey(User, related_name="friend_set", on_delete=models.CASCADE)

views.py

def profile(request):
    friends = Friend...

    context = {
        'friends': friends,
    }

    return render(request, ..., context)

How to write queryset to get list of usernames who are firends to specific user?

Upvotes: 1

Views: 1709

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

You can get the list of Users that are friends with a given user through:

friends = User.objects.filter(friendship_creator_set__friend=request.user)

(or use a specific user instead of request.user if you want to retrieve the friends of another one.)

or if you want to obtain the Users that request.user considers friends (so the relation in reverse), you can use:

friends = User.objects.filter(friend_set__user=request.user)

These are the User objects. We can also obtain the Friend objects, with:

friends = Friend.objects.filter(friend=request.user)

or we can obtain the user names with:

usernames = User.objects.filter(
    friendship_creator_set__friend=request.user
).value_list('username', flat=True)

Although it is usually better to work with model objects, not with the values of that column, since a model attaches special behavior to values. A User is more informative than the username of a User.

Upvotes: 4

Related Questions