我有这些模特:
class Author(models.Model):
#id = models.IntegerField(blank=True)
code = models.CharField(verbose_name="Author Code", max_length=100, unique=True)
firstname = models.CharField(verbose_name="First Name", max_length=200)
lastname = models.CharField(verbose_name="Last Name",max_length=200)
#Optional Fields
middlename = models.CharField(verbose_name="Middlename", max_length=200, null=True, blank=True)
email = models.EmailField(verbose_name="Author's Email",max_length=75, null=True, blank=True)
sex = models.CharField(verbose_name="Sex", max_length=1, choices=(('M', 'Male'), ('F', 'Female')), null=True, blank=True)
salutation = models.CharField(verbose_name="Salutation",max_length=10, null=True, blank=True)
suffix = models.CharField(verbose_name="Suffix", max_length=10, null=True, blank=True)
def __unicode__(self):
return u'%s %s (%s)' % (self.firstname, self.lastname, self.code)
class Book(models.Model):
#book title
#book_id = models.IntegerField(blank=True)
title = models.CharField(verbose_name="Book Title", max_length=200)
subtitle = models.CharField(verbose_name="Book Subtitle", max_length=200, null=True, blank=True)
#Reference information
accession_number = models.CharField(verbose_name="Accession Number", max_length=100)
call_number = models.CharField(verbose_name="Call Number", max_length=100)
isbn = models.CharField(verbose_name="ISBN Code", max_length=100, null=True, blank=True, unique=False)
dewey_class = models.ForeignKey(DeweyClass, verbose_name="Dewey Class", null=True, default=False, unique=False)
subject = models.CharField(verbose_name="Subject", max_length=100)
#authorship information
author = models.ManyToManyField(Author, verbose_name="Book Author")
pages = models.IntegerField(verbose_name="Number of Pages")
edition = models.CharField(verbose_name="Edition", max_length=100, null=True, blank=True)
volumes = models.CharField(verbose_name="Volume Number", max_length=100, null=True, blank=True)
#
现在,在前端,我想显示作者列表以及他们制作的图书。
类似的东西:
J.R.R。托尔金
答案 0 :(得分:0)
您可以使用重新组合模板标记:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
在您看来:
books_qs = Book.objects.all()
books = []
for book in books_qs:
for author in book.author.all():
books.append({'title' : book.title, 'author' : author.lastname})
在你的模板中:
{% regroup books by author as author_list %}
<ul>
{% for author in author_list %}
<li>{{ author.grouper}}
<ul>
{% for item in author.list %}
<li>{{ item.title}}</li>
{% endfor %}
</ul>
</li>
{% endfor %}