Simple JOIN in Django
-
13-09-2019 - |
Question
I'm trying to accomplish something akin to twitter on my website, where one user can follow another one. I want to select all User records that are following a User with a given ID. My follow relationship model look like:
class Following(models.Model):
user = models.ForeignKey(User, related_name='is_following')
followed = models.ForeignKey(User, related_name='is_followed')
And I'm using the django.contrib.auth.models User class.
Assuming I have a User object named "myUser" representing the followed person, what's the appropriate query to get everyone following them?
Solution
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.
OTHER TIPS
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.