DRF的安装和简单使用

本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/13339630.html

一: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即可看到接口

image-20200719135324919

9.进入127.0.0.8:8000/book/

image-20200719135405957

10.填入数据,点击按钮提交POST请求,即可添加数据

image-20200719135535449

二: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

image-20200719143208676

三: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

image-20200719145735671

posted @ 2020-07-19 14:33  轻描丨淡写  阅读(278)  评论(0编辑  收藏  举报