我撰寫了一些代碼來查找資料庫中的第一篇文章并將其輸出到我的頁面,但是我不確定如何遍歷資料庫。我以前做過類似的事情,但這是我第一次使用 django 和 bootstrap。
我的觀點目前是這樣的:
def gallery_view (request):
obj = GalleryPost.objects.get (id =1)
context = {
'object' : obj
}
return render(request, "gallery.html", context)
這對于 1 個物件來說效果很好,但正如您所看到的,它的集合 ID 為 1,因此我需要以某種方式迭代它以從我的資料庫中獲取每個專案并以某種方式正確輸出它們。
uj5u.com熱心網友回復:
看法:
def gallery_view(request):
qs = GalleryPost.objects.all()
context = {
'objects' : qs
}
return render(request, "gallery.html", context)
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for object in objects %}
<div>
{{object}}
</div>
{% empty %}
<p>No objects found</p>
{% endfor %}
</body>
</html>
除了 .all() 您還可以使用 .filter() 來過濾查詢集。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/360212.html
