1.安装:pip install djangorestframework==3.10.3
2. 在setting.py 的app中注册INSTALLED_APPS = [ ** ‘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 新建一个序列化类
新建一个py文件名字Serializer
from rest_framework.serializers import ModelSerializer
from app01.models import Book
class BookModelSerializer(ModelSerializer):
class Meta:
model = Book
fields = "__all__"
5 在视图中写视图类
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. 写路由关系
from app01 import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('book', views.BooksViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
]
urlpatterns += router.urls
7.浏览器请求
|