Berbagi teknologi

Objek Django QuerySet, metode get()

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Lihat bab sebelumnya untuk modelnya:

Objek Django QuerySet, metode filter()-Blog CSDN

Metode get() dari objek QuerySet Django digunakan untuk memperoleh objek tunggal dari database.

1. Tambahkan fungsi tampilan

Uji/app11/views.py

  1. from django.shortcuts import render
  2. from .models import Post
  3. def index(request):
  4. posts = Post.objects.all()
  5. return render(request, '11/index.html', {'posts': posts})
  6. # apps/books/views.py
  7. from django.shortcuts import render
  8. from .models import Book
  9. def book_list_view(request):
  10. # 使用filter()方法获取所有价格在1020之间的书籍
  11. # books = Book.objects.filter(price__gte=10, price__lte=20) # __gte是“greater than or equal to”(大于等于)的缩写,__lte是“less than or equal to”(小于等于)的缩写。
  12. # books = Book.objects.filter(price__gt=10) # 在Django的ORM(对象关系映射)查询中,__gt是过滤条件的一个特殊语法,用于表示“大于”(greater than)。
  13. books = Book.objects.filter(price__lt=29.99) # __lt 是“less than”(小于)的缩写。
  14. return render(request, '11/book_list.html', {'books': books})
  15. def get_book_view(request):
  16. try:
  17. # 使用get()方法获取标题为"Python Cookbook"的书籍
  18. book = Book.objects.get(id=19)
  19. # 现在book变量包含了匹配的书籍对象
  20. print(book)
  21. return render(request, '11/book_detail.html', {'book': book})
  22. except Book.DoesNotExist:
  23. # 如果没有找到匹配的书籍,返回错误信息
  24. return HttpResponse("Book not found.")
  25. except Book.MultipleObjectsReturned:
  26. # 如果找到多个匹配的书籍,返回错误信息
  27. return HttpResponse("Multiple books found with the same title.")

2. Tambahkan kode html

Uji/templat/11/detail_buku.html

  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>书籍列表</title>
  6. </head>
  7. <body>
  8. <h2>书籍:{{ book }}</h2>
  9. <h1>{{ book.title }}</h1>
  10. <p>作者: {{ book.author }}</p>
  11. <p>日期: {{ book.publication_date }}</p>
  12. <p>价格: {{ book.price }}</p>
  13. </body>
  14. </html>

3. Tambahkan alamat perutean

Uji/app11/urls.py

  1. from django.urls import path
  2. from . import views
  3. urlpatterns = [
  4. path('index/', views.index, name='index'),
  5. path('book_list_view/', views.book_list_view, name='book_list_view'),
  6. path('get_book_view/', views.get_book_view, name='get_book_view'),
  7. ]

4. Kunjungi halaman tersebut

http://127.0.0.1:8000/app11/dapatkan_tampilan_buku/

Terlihat data dengan ID 19 berhasil didapatkan.