Django模板不显示ForeignKey项目

时间:2019-06-24 07:07:22

标签: django

我是django的新手,我的外键项目没有显示问题,希望您能帮助我...谢谢。

这是我的models.py

class Reporter(models.Model):

    name = models.CharField(max_length=20)
    address = models.CharField(max_length=30)

    def __str__(self):
        return self.name


class News(models.Model):
    headline = models.CharField(max_length=50)
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

和我的views.py

def index(request):

    reportlist = Reporter.objects.all()

    context = {
        'reportlist': reportlist
    }

    return render(request, 'index.html', context)

和我的模板

{% block content %}

    {% for r in reportlist %}
    <p>{{r.name}}</p>
    {% for items in r.item_set.all%}
         <p>{{items.headline}}</p>
            {%endfor%} <br/>
    {%endfor%}

{% endblock %}

1 个答案:

答案 0 :(得分:1)

{% block content %}

    {% for r in reportlist %}
    <p>{{r.name}}</p>
    {% for items in r.news_set.all%}
         <p>{{items.headline}}</p>
            {%endfor%} <br/>
    {%endfor%}

{% endblock %}

您的型号名称为News,因此您需要model_name_set,即news_set