我有兩個型號,作者&本書在models.py如何訪問Django中基於類的視圖中的多個字段?
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age = models.IntegerField()
def __str__(self):
return '%s %s' %(self.first_name, self.last_name)
def __unicode__(self):
return '%s %s' %(self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100) #name = title
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
author = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __str__(self):
return self.title
def __unicode__(self):
return self.title
現在,我使用上市ListView中的所有書籍。和一本書的點擊我使用獲取信息的書下面的方法
class BookDetailView(generic.DetailView):
template_name = 'books/book_detail1.html'
model = Book
context_object_name = 'book_detail'
我能夠獲得冠軍,網頁,價格,評價,發佈者& publication_date,但沒有得到所有的作者(作者名單) 。雖然我只是簡單地打印它,但它在模板中打印無。我甚至嘗試使用for循環迭代,但在模板
views.py沒有做過
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<li>Price:{{ book_detail.price }}</li>
<li>Pub Date:{{ book_detail.publication_date }}</li>
<li>Title: {{ book_detail.title }}</li>
<li>Pages: {{ book_detail.pages }}</li>
<li>Rating: {{ book_detail.rating }}</li>
<li>Publisher: {{ book_detail.publisher }}</li>
<li>Author: {{ book_detail.author }}</li>
</ul>
</body>
</html>
誰能幫我出此?
需要更多信息,你如何試圖從模板中訪問作者(s)?你應該循環{{book.author.all}}或類似的東西。 –
向我們展示模板代碼... – solarissmoke
@solarissmoke編輯 –