Cris_Towi
Cris_Towi

Reputation: 625

Join in Django?

I'm trying to make an application in Django, but I need to do a JOIN in Django, Somethin like that:

SELECT User.name, Post.contain from User, Post where Post.User_id = User.id;

Hoy can i get the User.name?

My model is

from django.db import models
from django.contrib.auth.models import User


class Post(models.Model):
    titulo = models.CharField(max_length = 60)
    contenido = models.TextField(max_length = 140)
    fecha = models.DateTimeField(auto_now_add = True, blank = True)
    usuario = models.ForeignKey(User)

    def __unicode__(self):
        return self.titulo

really thank you for the help =)

Upvotes: 1

Views: 211

Answers (1)

Paulo Scardine
Paulo Scardine

Reputation: 77251

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_namemethod`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')

Upvotes: 2

Related Questions