我是django和python的新手。
这是一个示例代码,我用来说明我的问题:
class Book(models.Model):
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='book_subby')
submitted_date = models.DateField(auto_now=True)
book_title = models.CharField(max_length=200)
book_publisher = models.ForeignKey(Publishers)
class Publishers(models.Model):
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='publisher_subby')
submitted_date = models.DateField(auto_now=True)
book_publisher = models.CharField(max_length=200)
def book_list(request):
books = Book.objects.filter(submitted_by=request.user, submitted_date__lte=timezone.now()).order_by('submitted_date')
books_by_publisher =
return render(request, 'book/list_books.html', {
'books': books
})
{% for book in books %}
<ul> {{ book.book_publisher }}
<li> {{book.book_title }} </li>
{% endfor %}
显示:
出版商X
*书A
出版人Y
*书B
出版商X
*书C
出版人Y
*书D
我想要显示:
出版商X
*书A
*第C册
出版商Y
*书B
*书D
我尝试在模板中执行多个for循环,但无法使其工作。 如果有人能够在正确的方向上推动我如何解决这个问题,我将不胜感激。 谢谢,Andrea
答案 0 :(得分:0)
您可以这样做:
error
class Book(models.Model):
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='book_subby')
submitted_date = models.DateField(auto_now=True)
book_title = models.CharField(max_length=200)
book_publisher = models.ForeignKey(Publishers, related_name='books')
class Meta:
ordering = ['submitted_date'] # To keep this sorted by this field
def book_list(request):
publishers_with_books = Publishers.objects.prefetch_related('books').filter(submitted_by=request.user, books__isnull=False, books__submitted_date__lte=timezone.now())
return render(request, 'book/list_books.html', {
'publishers': publishers_with_books
})
希望这对你有帮助;)。