You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django模板中访问一对多关联关系的属性?

解决Django一对多关联的月份-条目展示问题

你的问题核心是MonthDetailView错误地使用了Entry模型,我们需要展示的是某个具体Month对象下的所有Entry,而非单个Entry的详情。此外模板中的链接写法和数据获取逻辑也存在问题,以下是具体修复步骤:

1. 修正视图(views.py)

将MonthDetailView改为基于Month模型,Django会自动为Month实例生成反向关联属性,用于获取该月份下的所有条目:

class MonthListView(generic.ListView):
    model = Month
    context_object_name = 'month_list'
    template_name = 'diary/month.html'


class MonthDetailView(generic.DetailView):
    model = Month
    context_object_name = 'month'
    template_name = 'diary/entries.html'


def index(request):
    month = Month.objects.all()
    entry = Entry.objects.all()

    context = {
        'month': month,
        'entry': entry,
    }

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

2. 修正月份列表模板(month.html)

使用Django的url模板标签生成正确的跳转地址,避免硬编码路径:

{% extends "base.html" %}

{% block title %}<title>Months</title>{% endblock %}

{% block content %}
<h1>Month</h1>
{% if month_list %}
    <ul>
        {% for month in month_list %}
        <li>
            <a href="{% url 'entries' month.pk %}">{{ month.month_name }}, {{ month.year_number }}</a>
        </li>
        {% endfor %}
    </ul>
{% else %}
    <p>There are no months to display</p>
{% endif %}
{% endblock %}

3. 修正条目展示模板(entries.html)

通过当前month对象的entry_set属性遍历所有关联的Entry:

{% extends "base.html" %}

{% block title %}<title>{{ month.month_name }}, {{ month.year_number }} Entries</title>{% endblock %}

{% block content %}
<h1>{{ month.month_name }}, {{ month.year_number }}</h1>
{% if month.entry_set.all %}
    {% for entry in month.entry_set.all %}
        <h3>{{ entry.title }}</h3>
        <p>{{ entry.date_created }}</p>
        <p>{{ entry.content }}</p>
    {% endfor %}
{% else %}
    <p>There are no entries in this month.</p>
{% endif %}
{% endblock %}

可选优化:添加get_absolute_url方法

如果希望更规范地生成跳转链接,可以在models.py的Month类中添加以下方法:

class Month(models.Model):
    # 原有字段和方法不变
    def get_absolute_url(self):
        from django.urls import reverse
        return reverse('entries', args=[str(self.id)])

之后模板中的链接可以简化为:

<a href="{{ month.get_absolute_url }}">{{ month.month_name }}, {{ month.year_number }}</a>

内容的提问来源于stack exchange,提问作者user20724081

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:20:37