Hi all,
I’ve got what is probably a relatively simple question. I’ve read through the related documentation but I’m still getting stumped.
I think it’s probably just a case of not writing the proper syntax. I would really appreciate any help and advice you can give.
SCENARIO:
• I’ve created a CustomUser and a related Profile model.
• Within the app it is possible for a user to follow another.
• This is handled via a Contact model linked to via a ManyToMany field.
The diagram below shows the relationship between two CustomUser models. Blue lines are the direction I’m interested in i.e. User A to User B.
TRYING TO ACCOMPLISH:
Once those following relationships are created, I’m trying to build a list of followers for a user. For example, on User A’s profile page, it should be possible to view a list of all the user’s that are following them.
PROBLEM:
The problem is my (lack of) knowledge of the Django query syntax means I cannot find a way to traverse the relationship within the views.py file. All I can return is a QuerySet of Profile models:
def user_followers(request, username):
user = get_object_or_404(get_user_model(), username=username)
followers = user.profile.followers.all()
return render(request, 'profile.html', {'user': user, 'followers': followers})
This just returns a list of Profiles.
I’ve tried lots of different variations (e.g. double underscore) to go that extra step and get the corresponding User models, but haven’t been able to find the correct syntax to do this yet.
ALTERNATIVES:
I can think of a couple of potential workarounds for this:
- In the views.py file, start from the CustomUser object and then filter the queryset based on whether they are following the currently-viewed user. However this seems excessive, as it would mean for every single user in the database, checking their list of followers.
- In the HTML template, update the list syntax to say something along the lines of
{% for member.user in members %}
however I’d really like to avoid customising my HTML when the logic should be easily accommodated in the view. - Similar to #2, but within views.py iterate over the list of Profiles to get another list of corresponding CustomUsers.
Of all these #3 feels the closest, but again I’m just finding my way in the dark without knowledge of the query syntax. Can anyone help point me in the right direction?
Many thanks in advance,
Tom