一:DRF安装使用
1.安装
pip3 install djangorestframework
2.在setting.py
的app
中注册
'rest_framework'
3.在models.py
中添加代码
class Book(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
author = models.CharField(max_length=32)
4.新建ser.py
序列化类,添加代码
from rest_framework.serializers import ModelSerializer
from app01.models import Book
class BookModelSerializer(ModelSerializer):
class Meta:
model = Book
fields = "__all__"
5.在view.py
中添加代码
from rest_framework.viewsets import ModelViewSet
from .models import Book
from .ser import BookModelSerializer
class BooksViewSet(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookModelSerializer
6.在urls.py
中替换如下代码
from django.contrib import admin
from django.urls import path
from app01 import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter() # 可以处理视图的路由器
router.register('book', views.BooksViewSet) # 向路由器中注册视图集
# 将路由器中的所以路由信息追到到django的路由列表中
urlpatterns = [
path('admin/', admin.site.urls),
]
# 这是什么意思?两个列表相加
# router.urls 列表
urlpatterns += router.urls
7.执行数据迁移命令
python manage.py makemigrations
python manage.py maigrate
8.进入127.0.0.1:8000
即可看到接口
9.进入127.0.0.8:8000/book/
10.填入数据,点击按钮提交POST请求,即可添加数据
二:django原生View
1.在view.py
中添加代码
from django.views import View
class Books(View):
# 设置了只能接收get请求
http_method_names = ['get',]
def get(self, request):
print(self.request)
return HttpResponse('OK')
2.在urls.py
中添加代码
path('books/', views.Books.as_view()),
3.访问网页127.0.0.1:8000/books
三:drf中的View
1.在view.py
中添加代码
from rest_framework.views import APIView
class BooksAPIView(APIView):
def get(self, request):
# 此时的request已经不是django原生的request了,而是drf自定义的request对象
print(self.request)
return HttpResponse('APIVIew OK')
2.在urls.py
中添加代码
path('booksaipview/', views.BooksAPIView.as_view()),
3.访问网页127.0.0.1:8000/booksaipview