In a django template, when you do a loop to display profile informations for many users, you call get_profile, thus generating as many SQL request :
{% for user in users %}
{{ user.username }} : {{ user.get_profile.birth_date }}
{% endfor %}
If you have 50 users to display, it will generate 50 SQL requests to get the profile for each user.
Is there an elegant way to reduce the number of requests ?
EDIT :
The final goal was to manage a list a items where an item has a user object as attribute. Example : Each question in stackoverflow has a user as a creator. How to list all recent questions while displaying the user profile informations in a minimum of SQL requests :
The template should be like that :
{% for question in recent_questions %}
{{ question.title }}
{{ question.body }}
{{ question.creator.username }}
{{ question.creator.get_profile.age }}
{{ question.creator.get_profile.country }}
{% endfor %}
But this will generate too many SQL requests ...
I would write my own templatetag for this case,
@register.simpletag(takes_context=True)
def load_profiles(context,users):
context['profiles']=ProfileClass.objects.select_related().filter(user__in=users)
return ''
template:
{% load_profiles users %}
{% for one in profiles%}
{{one.user.username}} : {{one.birth_date }}
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With