Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Reverse Query in Template

Tags:

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

like image 331
brsbilgic Avatar asked Jun 10 '11 12:06

brsbilgic


2 Answers

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 %}
like image 189
manji Avatar answered Sep 28 '22 08:09

manji


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 %}
like image 25
JamesO Avatar answered Sep 28 '22 08:09

JamesO