25

I have models like this

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __unicode__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)

I want to list all blogs in a page. I have written a view such that

def listAllBlogs(request):
    blogs= Blog.objects.all()
    return object_list(
        request,
        blogs,
        template_object_name = "blog",
        allow_empty = True,
        )

And I can display tagline of blog such that in view

{% extends "base.html" %}
{% block title %}{% endblock %}
{% block extrahead %}

{% endblock %}

{% block content %}
     {% for blog in blog_list %}
          {{ blog.tagline }}
     {% endfor %}
{% endblock %}

But I would like to show, such thing blog__entry__name but I don't know how can I achive this in template. Also, there may be no entry in a blog. How can I detect in template ?

Thanks

brsbilgic
  • 11,613
  • 16
  • 64
  • 94
  • 4
    Both answers below are correct, just two remarks. Define `related_name='entries'` for `blog` field, and you will be able to write `blog.entries`. And use `select_related()`, not to make N + 1 SQL queries. – DrTyrsa Jun 10 '11 at 13:02

2 Answers2

41

To access blog entries (Related Manager): blog.entry_set.all

To do other actions if blog have no entries, you have the {% empty %} tag that is executed when the set is empty.

{% block content %}
     {% for blog in blog_list %}
          {{ blog.tagline }}
          {% for entry in blog.entry_set.all %}
              {{entry.name}}
          {% empty %}
             <!-- no entries -->
          {% endfor %}
     {% endfor %}
{% endblock %}
manji
  • 47,442
  • 5
  • 96
  • 103
  • @brsbilgic [related_name](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name) – DrTyrsa Jun 10 '11 at 13:20
  • For a `OneToOneField` you can simply use: `blog.entry` (instead of `blog.entry_set`). https://docs.djangoproject.com/en/dev/topics/db/queries/#one-to-one-relationships – manji Jun 10 '11 at 13:27
  • That works great. Thank you! But what if the relationship were one-to-one blog = models.OneToOneField(Blog,unique=True) . What is the right way to do such thing in template like ` {{ blog.entry__headline }}` – brsbilgic Jun 10 '11 at 13:28
9

based on your code you could do the following.

{% block content %}
     {% for blog in blog_list %}
          {{ blog.tagline }}
          {% for entry in blog.entry_set.all %}
              {{entry.name}}
          {% endfor %}
     {% endfor %}
{% endblock %}
JamesO
  • 25,178
  • 4
  • 40
  • 42