Search code examples
pythondjangoormmodels

Django: Querying Multiple Foreign Keys


First off, I'm sure this is a simple question. I'm just getting started with Django and as all beginners do, I thought I'd build a simple blog.

I have a simple data model, a Post model that contains with a link to a user via a FK.

models.py

class Post(TimeStampedActivate):
    """
    A blog post
    """
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    excerpt = models.TextField(blank=True)
    body = models.TextField()
    publish_at = models.DateTimeField(default=datetime.datetime.now())
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=False, help_text='Is the blog post active?')
    user = models.ForeignKey(User, related_name='post_user')

    def __unicode__(self):
        return self.title

I then want a page that lists all of the Posts alongside the username of the person who created the post. My current view looks like this:

views.py

def index(request):
    posts = Post.objects.filter(active=True)   
    user = User.objects.get(id=1)
    return render(request, 'blog/index.html', {'posts': posts, 'user': user})

My template At present this just displays the users name that matches an ID of 1.

{% for post in posts %}
    <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
    <p>{{ post.excerpt|truncatewords:30 }}</p>
    <p>Posted by {{ user.first_name }} {{ user.last_name }}</p>
{% endfor %}

How would I modify my views.py file to ensure I get the first and last name of the user responsible for the post?


Solution

  • View:

    def index(request):
        posts = Post.objects.filter(active=True)   
        return render(request, 'blog/index.html', {'posts': posts})
    

    Template:

    {% for post in posts %}
        <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
        <p>{{ post.excerpt|truncatewords:30 }}</p>
        <p>Posted by {{ post.user.first_name }} {{ post.user.last_name }}</p>
    {% endfor %}