Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get_profile in django template loop leads to many SQL requests

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 ...

like image 672
Eric Avatar asked Dec 31 '25 20:12

Eric


1 Answers

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 %}
like image 91
Xun Yang Avatar answered Jan 03 '26 14:01

Xun Yang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!