Python系列视频教程: Django【13讲】第12讲 数据展示
继续上一讲
>>> books
[<Book: python book1>, <Book: python book2>]
>>> author1.book_set.all()
[<Book: python book2>]
>>> for a in Author.objects.all():
... for book in a.book_set.all():
... print book
...
...
python book2
python book1
python book1
如何在web中呈现这些数据
blog\views.py
from blog.models import Author,Book
from django.shortcuts import render_to_response# Create your views here.
def show_author(req):
authors=Author.objects.all()
return render_to_response("show_author.html",{"authors":authors})
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
#from blog.models import Author,Book
admin.autodiscover()urlpatterns = patterns('',
# Examples:
# url(r'^$', 'csvt06.views.home', name='home'),
url(r'^blog/show_author/$', 'blog.views.show_author'),
url(r'^admin/', include(admin.site.urls)),
)
show_author.html
<body>
<h1>hello</h1>
{%for author in authors %}
<div>
{{forloop.counter}} {{author}}
</div>
{%endfor %}
<div>
共有 {{authors.length}}记录
</div>
</body>
http://127.0.0.1:8000/blog/show_author/
hello
修改show_author.html
<body>
<h1>hello author</h1>
{%for author in authors %}
<div>
{{forloop.counter}} {{author}}
{%for book in author.book_set.all %}
<li>{{forloop.counter}} {{book}} </li>
{%endfor %}
</div>
<div>
{%endfor %}
共有 {{authors.length}}记录
</div>
</body>
http://127.0.0.1:8000/blog/show_author/
hello author
- 1 python book2
- 2 java book1
- 1 python book1
- 1 python book1
- 2 java book1
修改urs.py
url(r'^blog/show_book/$', 'blog.views.show_book'),
修改blog\views.py
def show_book(req):
books=Book.objects.all()
return render_to_response("show_book.html",{"books":books})
blog\templates\show_book.html
<body>
<h1>hello book</h1>
{%for book in books %}
<div>
{{forloop.counter}} {{book}}
{%for author in book.authors.all %}
<li>{{forloop.counter}} {{author}} </li>
{%endfor %}
</div>
<div>
{%endfor %}
共有 {{books.length}}记录
</div>
</body>http://127.0.0.1:8000/blog/show_book/
hello book
1 python book1
- 1 Ben
- 2 Cool
2 python book2
- 1 Alen
3 java book1
- 1 Alen
4 java book1
- 1 Cool
共有 记录