展示书功能:
views:
#定义展示书功能:
def book(request):
#查询所有书籍:
all_books = models.Book.objects.all()
for book in all_books:
print(book)
print(book.id)
print(book.pk)
print(book.pub_id) #所关联的出版社对象的id 对象.外键_id
print(book.pub) #所关联的出版社对象 对象.外键
return render(request,"book.html",{"all_books":all_books})
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>id</th>
<th>书名</th>
<th>出版社名字</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book in all_books %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book.pk }}</td>
<td>{{ book.name }}</td>
<td>{{ book.pub }}</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
效果如下: