django prefetch_related 查询之后,模板层如何使用?
prefetch_related查询出来的数据,在模板层如何调用?
回答:
class Author(models.Model): name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
然后,用 prefetch_related 来获取所有作者和他们的书:
def author_list(request): authors = Author.objects.all().prefetch_related('books')
return render(request, 'author_list.html', {'authors': authors})
author_list.html ;:
{% for author in authors %}
<h2>{{ author.name }}</h2>
<ul>
{% for book in author.books.all %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% endfor %}
以上是 django prefetch_related 查询之后,模板层如何使用? 的全部内容, 来源链接: utcz.com/p/938893.html