1、安装DRF
pip install djangorestframework
2、将DRF注册到APP中
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.apps.AppConfig', 'rest_framework', # 将DRF注册到APP中 ]
3、定义自己的模型类(数据表)
from django.db import models class Book(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) pubDate = models.DateField() author = models.CharField(max_length=32) class Meta: db_table = "book"
4、定义序列化器
from rest_framework import serializers # 定义序列化器 # BookSerializer为定义的序列化器名 # 需要继承:serializers.ModelSerializer类 class BookSerializer(serializers.ModelSerializer): class Meta: # model = Book:表示使用Book模型类的数据库表 model = Book # fields = "__all__":表示使用表中的所有字段 fields = "__all__"
5、定义路由
from django.urls import path, re_path from app.views import BookView from app.views import BookDetailView urlpatterns = [ path('admin/', admin.site.urls), path('book/', BookView.as_view()), re_path('book/(?P<pk>\d+)/', BookDetailView.as_view()), ]
6、定义视图类
# 需要导入generics from rest_framework import generics # BookView视图:继承generics.ListCreateAPIView # 实现:查看所有数据 和 新增数据 class BookView(generics.ListCreateAPIView): # queryset:拿到Book表的所有数据 queryset = Book.objects.all() # serializer_class:指定使用哪一个序列化器 serializer_class = BookSerializer # BookDetailView视图:继承generics.RetrieveUpdateDestroyAPIView # 实现:查看某一条数据、更新数据、删除数据 class BookDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializer
7、到此,接口实现完成
8、通过浏览器访问接口
9、通过postman工具访问接口
标签:GenericAPIView,子类,视图,django,Book,generics,contrib,import,class From: https://www.cnblogs.com/zhangyh-blog/p/17439037.html