urls.py
"""
URL configuration for drf project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from book import views
urlpatterns = [
path('admin/', admin.site.urls),
path('book/', views.BookView.as_view()),
path('book/<int:pk>', views.BookDetailView.as_view()),
]
檢視views.py
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView
from book.models import Book
class BookSerializer(serializers.ModelSerializer):
# 如果有部分自定義的欄位,只需要照常定義,並exclude排除原來的欄位即可
asbgjasg_price = serializers.IntegerField(source='price')
class Meta:
# 指定類名
model = Book
# fields為白名單模式,指的是需要序列化的欄位,__all__表示全部欄位
# 包括pk(自動生成的自增主鍵),但是這裡的值中指的是資料庫中的欄位名稱
# 儘管模型上自動生成的主鍵的屬性為pk,但是存入資料庫中的名稱是id。
# 因此不想要pk的值,就排除id即可
# 白名單模式一般直接使用all
# fields = '__all__'
exclude = ['id', 'price']
# 查詢全部以及新增單個
class BookView(APIView):
def get(self, request):
booklist = Book.objects.all()
print('booklist', booklist)
serializer = BookSerializer(booklist, many=True)
return Response(serializer.data)
def post(self, request):
print(request.data)
serializer = BookSerializer(data=request.data)
is_valid = serializer.is_valid()
print('is_valid', is_valid)
# 存放錯誤資訊(需要先訪問is_valid方法)
print(serializer.errors)
if not is_valid:
return Response(serializer.errors)
# 下面處理透過的邏輯
serializer.save()
return Response({'msg': '新增成功', 'status': True})
class BookDetailView(APIView):
def get(self, request, pk):
print('引數方法呼叫')
book = Book.objects.get(pk=pk)
serializer = BookSerializer(book)
return Response(serializer.data)
def put(self, request, pk):
book = Book.objects.get(pk=pk)
print(request.data)
# 需要同時獲取模型例項和資料
serializer = BookSerializer(book, data=request.data)
if serializer.is_valid():
serializer.save()
print('data: ', serializer.data)
return Response({'msg': '修改成功', 'status': True})
else:
return Response(serializer.errors)
def delete(self, request, pk):
# 不涉及序列化器
book = Book.objects.get(pk=pk)
book.delete()
return Response({'msg': '刪除成功', 'status': True})