amankarn
amankarn

Reputation: 71

how to filter users who are not being followed in django

Friends, I am using django-friendship with django 1.9 to implement user follows. But on a 'users to follow' page, I want to filter those users who aren't being followed by the current user. How should I implement this?

Here is my views.py

def users_to_follow(request):
    follow = Follow.objects.following(request.user)
    all_users = User.objects.all().exclude(follow)
    return render(request,"auths/users_to_follow.html",locals())

and here is my users_to_follow.html

{% for u in all_users %}
  {{ u.username }}
  <a href="{% url 'follow' u.username %}">Follow</a>
{% endfor %}

I think there is something wrong with views.py . But i haven't been able to figure it out. Help me friends.

Upvotes: 1

Views: 57

Answers (3)

iulian
iulian

Reputation: 5822

According to Django QuerySet documentation (emphasis mine):

Field lookups are how you specify the meat of an SQL WHERE clause. They’re specified as keyword arguments to the QuerySet methods filter(), exclude() and get().

So, your exclude() method call can be adjusted as

all_users = User.objects.all().exclude(pk=follow)

And that's it!

Upvotes: 0

Selcuk
Selcuk

Reputation: 59238

exclude does not work this way. You can try the following:

def users_to_follow(request):
    all_users = User.objects.exclude(following__follower=request.user)
    return render(request,"auths/users_to_follow.html",locals())

Upvotes: 0

masnun
masnun

Reputation: 11906

The follow name (variable) is a list of user objects. You can get the IDs of those users like these:

follow = Follow.objects.following(request.user)
follow_ids = [x.id for x in follow]

And then use exclude like this:

to_follow = User.objects.all().exclude(id__in=follow)

The to_follow list should contain the users you want.

Upvotes: 1

Related Questions