Django Reverse Query in Template

让人想犯罪 __ 提交于 2019-12-18 11:07:56

问题


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


回答1:


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 %}



回答2:


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 %}


来源:https://stackoverflow.com/questions/6306568/django-reverse-query-in-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!