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

Django多对多关联:如何在循环中获取作者关联书籍名称

解决方案

问题根源在于当前代码仅固定获取了ID为1的作者关联书籍,模板循环所有作者时复用同一批数据,导致无法匹配每个作者对应的书籍。以下是修正步骤:

1. 优化视图代码

利用Django反向关联特性,直接从作者对象获取关联书籍,同时通过prefetch_related预取数据避免重复查询:

from .models import Author, Book

def manytomany(request):
    # 预取关联书籍,提升查询性能
    authors = Author.objects.all().prefetch_related('author')
    context = {
        'authors': authors,
    }
    return render(request, 'many-to-many.html', context)

2. 修改模板匹配作者与书籍

在模板循环中,针对每个作者对象,直接遍历其反向关联的书籍集合:

<div class="col-lg-12">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>作者名称</th>
                <th>书籍</th>
            </tr>                       
        </thead>
        <tbody>
            {% for author in authors %}
            <tr>               
                <td>{{ author.author_name }}</td>                           
                <td>
                    {% for book in author.author.all %}
                        {{ book.book_title }}{% if not forloop.last %}, {% endif %}
                    {% empty %}
                        无关联书籍
                    {% endfor %}
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

可选优化:提升代码可读性

当前related_name='author'命名易混淆,建议修改为更清晰的名称(如books),修改models.py:

class Book(models.Model): 
    # ... 其他字段 ...
    authors = models.ManyToManyField(Author, related_name='books')

对应视图和模板中需同步改为author.books.all(),代码逻辑更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:40:29