Django使用prefetch_related查询多对多关系后如何在模板渲染数据
模板渲染操作步骤
你在视图中已经通过prefetch_related预取了每本书关联的所有书店数据,结合你设置的default_related_name = 'stores',直接在模板中嵌套遍历即可,无需额外处理。
示例模板(mtm.html)代码
<!DOCTYPE html> <html> <head> <title>书店书籍列表</title> </head> <body> <h2>所有书籍及在售书店</h2> <ul> {% for book in books %} <li> 书籍名称:{{ book.name }}<br> 售价:{{ book.price }}元<br> 在售书店: <ul> {% for store in book.stores.all %} <li>{{ store.name }}</li> {% empty %} <li>暂无书店在售</li> {% endfor %} </ul> </li> {% endfor %} </ul> </body> </html>
注意事项
- 遍历关联对象时必须调用
all()方法,也就是写book.stores.all,不能只写book.stores prefetch_related已经完成了关联数据的预加载,嵌套遍历不会产生额外的数据库查询,不会出现N+1性能问题- 如果你没有设置
default_related_name,反向关联查询的默认写法是book.store_set.all
内容的提问来源于stack exchange,提问作者gio
相关产品推荐
相关产品推荐

