[Answered ]-Simple JOIN in Django

3👍

mipadi’s answer is missing ‘.all‘.

In a view, the queryset

followers = my_user.is_followed.all()

returns a list of Following objects where my_user is being followed. To get the user that is following from a Following object f, use f.user

If followers is in the template context, you could do the following.

{% for f in followers %}

  {{ f.user }}

{% endfor %}

You might find the Django documentation for many to many relationships useful.

-1👍

That’s where the related_name attribute comes into play — it allows you to follow a relationship backwards. So, to get all the users following a particular user, you’d use my_user.is_followed.

Obviously you might want to rename your attributes to reflect these relationships, since followed and is_followed might be a bit confusing, but that’s how you’d do it.

👤mipadi

Leave a comment