选择方式渲染在页面上显示
举例说明:
表设计
1 from django.db import models 2 3 4 class UserGroup(models.Model): 5 title = models.CharField(max_length=32) 6 7 8 class UserInfo(models.Model): 9 user_type_choices = ( 10 (1, '普通用户'), 11 (2, 'vip'), 12 (3, 'svip'), 13 ) 14 user_type = models.IntegerField(choices=user_type_choices) 15 username = models.CharField(max_length=32, unique=True) 16 password = models.CharField(max_length=64) 17 group = models.ForeignKey('UserGroup', on_delete=models.CASCADE) 18 roles = models.ManyToManyField('Role') 19 20 21 class UserToken(models.Model): 22 user = models.OneToOneField(to='UserInfo', on_delete=models.CASCADE) 23 token = models.CharField(max_length=64) 24 25 26 class Role(models.Model): 27 title = models.CharField(max_length=32)
路由
1 from django.contrib import admin 2 from django.urls import path, re_path, include 3 4 urlpatterns = [ 5 path('admin/', admin.site.urls), 6 re_path('api/', include('api.urls')), 7 ]
分发的路由
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from django.urls import path, re_path, include 5 from api import views 6 7 urlpatterns = [ 8 # 渲染器 9 re_path('(?P<version>[v1|v2]+)/test/$', views.TestView.as_view()), 10 ]
视图:
1 # #############################渲染器############################ 2 from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer, AdminRenderer 3 4 5 class TestView(APIView): 6 renderer_classes = [JSONRenderer, BrowsableAPIRenderer, AdminRenderer] 7 8 def get(self, request, *args, **kwargs): 9 roles = models.Role.objects.all() 10 pg = MyCursorPagination() 11 # 在数据库中获取分页的数据 12 pg_roles = pg.paginate_queryset(queryset=roles, request=request, view=self) 13 # 对数据序列化 14 ser = PagerSerializer(instance=pg_roles, many=True) 15 ret = pg.get_paginated_response(ser.data) 16 return ret
全局配置:
1 REST_FRAMEWORK = { 2 # 渲染器 3 'DEFAULT_RENDERER_CLASSES': ['rest_framework.renderers.JSONRenderer', 4 'rest_framework.renderers.BrowsableAPIRenderer', 5 'rest_framework.renderers.AdminRenderer'] 6 7 }