1.安装
pip install jdangorestframework
pip install jdango-filter
配置
# 在django项目中的settings.py中的 INSTALLED_APPS 中配置django-rest-framework
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # 添加rest-framework应用
]
3.路由分发
"""项目的urls.py中做路由分发"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# 路由分发
path('api/v1/user/', include('user.urls')),
path('api/v1/goods/', include('goods.urls')),
path('api/v1/carts/', include('carts.urls')),
path('api/v1/orders/', include('orders.urls')),
]
4.定义资源
"""在应用的urls.py中定义资源"""
from django.urls import path
from rest_framework.routers import SimpleRouter
from user.views import UserView
router = SimpleRouter() # 获取路由对象
router.register('auth', UserView) # 注册资源,生成url
"""auth: 注册的资源. UserView: 用什么类视图取处理资源,这个class是自己定义的"""
urlpatterns = [
]
# 拼接资源, 将rest提供的接口添加到urlpatterns上
# 类似: /api/v1/user/auther/ 或者 /api/v1/user/auther/id/
urlpatterns += router.urls
5.类视图的书写
from rest_framework import viewsets, mixins
from user.models import AXFUser
from user.models import UserSerializer
class UserView(viewsets.GenericViewSet,
mixins.CreateModelMixin,
mixins.ListModelMixin):
# 对应资源要查询的数据(其实就是在获取对应的数据库数据)
queryset = AXFUser.objects.all()
# 定义一个类,将queryset中的数据序列化
serializer_class = UserSerializer
6.序列化模块的书写 serializers.py
from rest-framework import serializers
from user.models import AXFUser
class UserSerializer(serializers.ModelSerializer):
"""用户模型字段序列化"""
class Meta:
model = AXFUser # 告诉序列化器要序列化的模型
fields = '__all__' # 序列化模型的全部字段
# fields = ['u_username', 'u_password', 'u_email', 'id'] # 也可以指定要序列化的字段
网友评论