1👍
✅
You need to add a related_name
to the foreign key. Like this:
rank = models.ForeignKey(Rank, related_name='users')
Then the users can be accessed in a loop like this:
{% for user in rank.users.all %}
{{ user }}
{% endfor %}
0👍
For each Rank
object, you can reverse the relationship and get all of the Users
related to that Rank
# models.py
# - Use `related_name` for making relationship that are easy to read and follow
# - https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name
class User(...):
rank = models.ForeignKey(Rank, related_name="users")
# view.py
# - Use prefetch_related allows us to cut down our queries when iterating as we do an up-front join
# - https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related
...
def get_queryset(self):
return Rank.objects.prefetch_related('users')('rank_num')
# template.py
{% for rank in Rank_List %} # You shouldn't capitalise your template variables
{% for user in rank.users.all %}
{{ user }}
{% endfor %}
{% endfor %}
Finally, you should use the built-in User
model that django’s auth
module provides
Source:stackexchange.com