今天講如何顯示全部資料
先用 http://localhost:8000/admin/ 的方式建幾筆 類別 資料吧
先把 路由 views 設定好
shop/urls.py 加上 store url
urlpatterns = [
path('admin/', admin.site.urls),
path('store/', include('store.urls')),
...
]
新增 store/urls.py
from django.urls import path
from store import views
urlpatterns = [
path('category/', views.category)
]
store/views.py
from django.shortcuts import render
# Create your views here.
def category(request):
return render(request, 'store/category.html')
store/templates/store/category.html
<!doctype html>
<html>
<head></head>
<body>
category page
</body>
</html>
http://localhost:8000/store/category/
確定頁面跟views.py隊的之後開始寫撈資料程式
django ORM(Object Relational Mapping)
功能是可以用類似物件的方式對應到資料表及欄位,來做到資料表的增刪修查
這裡就是使用models.py 定義的類別來做mapping
query all
https://docs.djangoproject.com/en/2.0/topics/db/queries/#retrieving-all-objects
<model_name>.objects.all() 撈全部資料
並且把結果傳到前端,是queryset型態類似list
可以用print()方式,印出來會比較好懂
store/views.py
from store.models import Category
def category(request):
categorys = Category.objects.all()
return render(request, 'store/category.html', {'categorys':categorys})
前端這裡用forloop class.label
<class>.<field> 點後是指欄位
這裡是show name欄位
store/templates/store/category.html
...
<body>
{% for category in categorys %}
{{ category.name }}
{% endfor %}
</body>
...
可以再用 HTML 的 table顯示出來
store/templates/store/category.html
...
<body>
<table>
<tr>
<th>類別</th>
</tr>
{% for category in categorys %}
<tr>
<td>{{ category.name }}</td>
</tr>
{% endfor %}
</table>
</body>
...
結果圖
就完成了顯示多筆資料