2👍
Most of the time, you should not worry about joins. This is ORMs job.
posts = Post.objects.filter(user=user)
After the first query, the user should be in the ORM cache, so don’t worry about performance unless you detect a performance bottleneck (premature optimization is the root of all evil).
{% for post in posts %}
{% if forloop.first %}<h1>{{ post.user.name }}{% endif %}
<li>{{ post.contain }}</li>
{% endfor %}
If you really want to be a control freak:
posts = Post.objects.select_related().filter(user=user_id)\
.values('user__name', 'contain')
[update]
django.contrib.auth.models.User
lacks a field called name
. It has username
, first_name
and last_name
. There is also the get_full_name
method`suggested by karthikr.
What is the result of the following?
Post.objects.filter(user=user_id)
The template should be:
{% for post in posts %}
{% if forloop.first %}
<h1>{% trans 'Posts for' %}
{{ post.usuario.get_full_name|default:post.usuario.username }}
</h1>
<ul>
{% endif %}
<li>{{ post.contenido }}</li>
{% if forloop.last %}
</ul>
{% endif %}
{% endfor %}
Try the same queryset without the filter to see if the problem is with the filter (like the user having no posts).
Post.objects.select_related().filter(usuario=user_id)\
.values('usuario__username', 'contenido')
Source:stackexchange.com