09.ModelViewSet
# 01.DRF初始化
- 1.DRF框架的8个核心功能
1.认证(用户登录校验用户名密码或者token是否合法)
2.权限(根据不同的用户角色,可以操作不同的表)
3.限流(限制接口访问速度)
4.序列化(返回json)
5.分页
6.版本(接口版本号,用 v1/v2/v3)
# api.example.com/v1/login # 只有用户名密码登录
# api.example.com/v2/login # 手机号,微信 登录
7.过滤(username=zhangsan)
8.排序(ordering=-id)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
2.相关包
'''1.序列化相关'''
serializer
ModelSerializer
'''2.DRF视图函数继承'''
APIView
ModelViewSet
1
2
3
4
5
6
2
3
4
5
6
# 1.1 安装DRF
pip install djangorestframework==3.11.0 # 安装djangorestframework
pip install django-filter==2.3.0 # 安装过滤器
1
2
2
# 1.2 在syl/settings.py中注册
INSTALLED_APPS = [
'django_filters',
'rest_framework',
]
1
2
3
4
2
3
4
# 1.3 syl/settings.py配置DRF
# 过滤器
# 1,安装 django-filter
# 2,注册应用
# 3,配置settings, 在view里配置可过滤的字段
# 4,使用 查询字符串携带过滤信息
REST_FRAMEWORK = {
# 文档报错: AttributeError: ‘AutoSchema’ object has no attribute ‘get_link’
# 用下面的设置可以解决
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema',
# 默认设置是:
# 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.openapi.AutoSchema',
# 异常处理器
# 'EXCEPTION_HANDLER': 'user.utils.exception_handler',
# Base API policies
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
],
# 1.认证器(全局):用户登录校验用户名密码或者token是否合法
'DEFAULT_AUTHENTICATION_CLASSES': [
# 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 在DRF中配置JWT认证
# 'rest_framework.authentication.SessionAuthentication', # 使用session时的认证器
# 'rest_framework.authentication.BasicAuthentication' # 提交表单时的认证器
],
#2.权限配置(全局): 顺序靠上的严格(根据不同的用户角色,可以操作不同的表)
'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.IsAdminUser', # 管理员可以访问
# 'rest_framework.permissions.IsAuthenticated', # 认证用户可以访问
# 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 认证用户可以访问, 否则只能读取
# 'rest_framework.permissions.AllowAny', # 所有用户都可以访问
],
#3.限流(防爬虫)
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
#3.1限流策略
'DEFAULT_THROTTLE_RATES': {
'user': '100/hour', # 认证用户每小时100次
'anon': '3/day', # 未认证用户每天能访问3次
},
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'rest_framework.negotiation.DefaultContentNegotiation',
'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata',
'DEFAULT_VERSIONING_CLASS': None,
#4.分页(全局):全局分页器, 例如 省市区的数据自定义分页器, 不需要分页
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
# 每页返回数量
'PAGE_SIZE': 10, # 默认 None
#5.过滤器后端
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
# 'django_filters.rest_framework.backends.DjangoFilterBackend', 包路径有变化
],
#5.1过滤排序(全局):Filtering 过滤排序
'SEARCH_PARAM': 'search',
'ORDERING_PARAM': 'ordering',
'NUM_PROXIES': None,
#6.版本控制:Versioning 接口版本控制
'DEFAULT_VERSION': None,
'ALLOWED_VERSIONS': None,
'VERSION_PARAM': 'version',
# Authentication 认证
# 未认证用户使用的用户类型
'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser',
# 未认证用户使用的Token值
'UNAUTHENTICATED_TOKEN': None,
# View configuration
'VIEW_NAME_FUNCTION': 'rest_framework.views.get_view_name',
'VIEW_DESCRIPTION_FUNCTION': 'rest_framework.views.get_view_description',
'NON_FIELD_ERRORS_KEY': 'non_field_errors',
# Testing
'TEST_REQUEST_RENDERER_CLASSES': [
'rest_framework.renderers.MultiPartRenderer',
'rest_framework.renderers.JSONRenderer'
],
'TEST_REQUEST_DEFAULT_FORMAT': 'multipart',
# Hyperlink settings
'URL_FORMAT_OVERRIDE': 'format',
'FORMAT_SUFFIX_KWARG': 'format',
'URL_FIELD_NAME': 'url',
# Encoding
'UNICODE_JSON': True,
'COMPACT_JSON': True,
'STRICT_JSON': True,
'COERCE_DECIMAL_TO_STRING': True,
'UPLOADED_FILES_USE_URL': True,
# Browseable API
'HTML_SELECT_CUTOFF': 1000,
'HTML_SELECT_CUTOFF_TEXT': "More than {count} items...",
# Schemas
'SCHEMA_COERCE_PATH_PK': True,
'SCHEMA_COERCE_METHOD_NAMES': {
'retrieve': 'read',
'destroy': 'delete'
},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# 02.DRF使用
- 认证、权限、限流、分页、过滤、序列化
# 2.1 user/urls.py
- ModelViewSet注册路由三部曲
from django.urls import include, path
from user import views
from rest_framework.routers import SimpleRouter, DefaultRouter
# 自动生成路由方法, 必须使用视图集
# router = SimpleRouter() # 没有根路由 /user/ 无法识别
router = DefaultRouter() # 1.有根路由
router.register(r'user', views.UserViewSet) # 2.配置路由
urlpatterns = [
path('index/', views.index),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) # 认证地址
]
urlpatterns += router.urls # 3.模块地址
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[<URLPattern '^user/$' [name='user-list']>,
<URLPattern '^user\.(?P<format>[a-z0-9]+)/?$' [name='user-list']>,
<URLPattern '^user/actived/$' [name='user-actived']>,
<URLPattern '^user/actived\.(?P<format>[a-z0-9]+)/?$' [name='user-actived']>,
<URLPattern '^user/unactived/$' [name='user-unactived']>,
<URLPattern '^user/unactived\.(?P<format>[a-z0-9]+)/?$' [name='user-unactived']>, <URLPattern '^user/(?P<pk>[^/.]+)/$' [name='user-detail']>, <URLPattern '^user/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='user-detail']>, <URLPattern '^$' [name='api-root']>, <URLPattern '^\.(?P<format>[a-z0-9]+)/?$' [name='api-root']>] DRF
1
2
3
4
5
6
2
3
4
5
6
# 2.2 serializers.py
创建
user/serializers.py
写序列化器功能一:数据校验,
创建/修改数据
- 在创建数据或者修改数据时校验用户提交的数据是否合法
- 用户名必须是8位以上,邮箱、手机号是合法的
功能二:序列化
- 把通过model查询的queryset对象转换成JSON格式
from rest_framework import serializers
from user.models import User
def address_validate(data):
# data:是用户提交的地址这个字段的数据(河南省 郑州市)
# 独立校验器
# raise serializers.ValidationError('请填写实际地址') # 有错就抛出异常
# 没错就返回数据
return data
class UserSerializer(serializers.ModelSerializer):
# 1.独立校验器:重新设定字段, 替换掉模型中的设定, 重新设定地址的长度为5
# address_validate是自定义的数据校验函数
address = serializers.CharField(max_length=255, min_length=5, validators=[address_validate])
# 2.单一字段验证(validate_字段名), 验证地址
def validate_address(self, data):
if data == '测试':
raise serializers.ValidationError('请填写实际地址') # 有错就抛出异常
return data # 没错就返回结果
def validate_phone(self, data):
# 不符合手机号格式
# raise serializers.ValidationError('手机号格式不正确')
model = self.root.Meta.model
num = model.objects.filter(phone=data).count()
if num > 0:
raise serializers.ValidationError('手机号已存在')
return data
# 3.所有属性验证器
def validate(self, attrs):
# attrs:{"username":"zhangsan", "phone":"18538752511", ....}
# 所有属性验证器
# self.context 中有request和view上下文
# self.context['view'].action 可以取到动作
# attrs 是需要序列化的数据
# raise serializers.ValidationError('xxx错误') # 有问题报错
return attrs # 没问题返回数据
class Meta:
model = User # 具体对哪个表进行序列化
fields = '__all__' # 所有字段
# fields = ('id', ) # 临时添加字段也需要写在这里
# exclude = ['id'] # 排除 id 字段
# read_only_fields = ('',) # 指定字段为 read_only,
class UserUnActiveSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'is_active') # 临时添加字段也需要写在这里
# fields = '__all__' # 所有字段
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 2.3 user/views.py
from django.http import HttpResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from rest_framework.permissions import BasePermission, SAFE_METHODS
from user.models import User
from user.serializers import UserSerializer, UserUnActiveSerializer
def index(request):
# 需要认证才能访问的视图
return HttpResponse('hello')
# 分页(局部):自定义分页器 局部
class PageNum(PageNumberPagination):
# 查询字符串中代表每页返回数据数量的参数名, 默认值: None
page_size_query_param = 'page_size'
# 查询字符串中代表页码的参数名, 有默认值: page
# page_query_param = 'page'
# 一页中最多的结果条数
max_page_size = 2
# 自定义权限(局部)
class MyPermission(BasePermission):
# has_permission 是用户对这个视图有没有 GET POST PUT PATCH DELETE 权限的分别判断
def has_permission(self, request, view):
print('has_perm')
# print(view.kwargs.get("pk"), request.user.id)
"""判断用户对模型有没有访问权"""
# 任何用户对使用此权限类的视图都有访问权限
if request.user.is_superuser:
# 管理员对用户模型有访问权
return True
elif view.kwargs.get('pk') == str(request.user.id):
# 携带的id和用户的id相同时有访问权
return True
return False
# has_object_permission 是用户过了 has_permission 判断有权限以后,再判断这个用户有没有对一个具体的对象有没有操作权限
# 这样设置以后,即使是django admin管理员也只能查询自己user标的信息,不能查询其他用户的单条信息
def has_object_permission(self, request, view, obj):
print('has_object_perm')
"""获取单个数据时,判断用户对某个数据对象是否有访问权限"""
if request.user.id == obj.id:
return True
return False
class UserViewSet(viewsets.ModelViewSet):
"""
完成产品的增删改查
"""
queryset = User.objects.all()
serializer_class = UserSerializer # 优先使用 get_serializer_class 返回的序列化器
# # 1.认证:自定义认证类, 自定义会覆盖全局配置
# authentication_classes = (BasicAuthentication, SessionAuthentication)
# # 2.权限:自定义权限类
# permission_classes = (MyPermission,)
# 3.分页:自定义分页器 覆盖全局配置
pagination_class = PageNum
# 4.限流:自定义限流类
throttle_classes = [UserRateThrottle]
# 5.过滤:指定过滤方法类, 排序方法类, 一个或多个
filter_backends = (DjangoFilterBackend, OrderingFilter) # 同时支持过滤和排序
# 5.1指定排序字段, 不设置, 排序功能不起效
ordering_fields = ('date_joined', 'id') # ?ordering=-id
# 5.2指定过滤字段, 不设置, 过滤功能不起效
filter_fields = ('username', 'phone', 'is_active') # ?username=tom&phone=&is_active=true
# 根据不同的请求, 获得不同的序列化器
def get_serializer_class(self):
if self.action == 'unactived':
return UserUnActiveSerializer
else:
return UserSerializer
@action(methods=['get'], detail=False)
def unactived(self, request, *args, **kwargs):
# 获取查询集, 过滤出未激活的用户
qs = self.queryset.filter(is_active=False)
# 使用序列化器, 序列化查询集, 并且是
ser = self.get_serializer(qs, many=True)
return Response(ser.data)
@action(methods=['get'], detail=False)
def actived(self, request, *args, **kwargs):
# 获取查询集, 过滤出未激活的用户
qs = self.queryset.filter(is_active=True)
# 使用序列化器, 序列化查询集, 并且是
ser = self.get_serializer(qs, many=True)
return Response(ser.data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 03.测试接口
# 3.1 查询 接口
- 查询路由
#1.查询所有用户
http://192.168.56.100:8888/user/user/
#2.查询id=1的用户
http://192.168.56.100:8888/user/user/1/ #3.查询 用户名(tom),激活的用户
http://192.168.56.100:8888/user/user/?username=tom&phone=&is_active=true
#4.查询所有用户 用id 反向排序
http://192.168.56.100:8888/user/user/?ordering=-id
#5.查询用户表中第一页,每页显示一条数据
http://192.168.56.100:8888/user/user/?page=1&page_size=1
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- 增加(POST)
#1.增加用户
http://192.168.56.100:8888/user/user/
1
2
2
- 修改(PUT)
# 修改用户信息
http://192.168.56.100:8888/user/user/1/
1
2
2
- 删除(DELETE)
# 删除用户
http://192.168.56.100:8888/user/user/1/
1
2
2
# 3.2 自定义认证权限
# 3.2.1 测试全局权限
功能
- 在浏览器中,打开任意接口,未登录用户只能发送get请求,只有登录用户才能发送post等请求
# http://192.168.56.100:8888/user/user/
'''syl/settings.py中设置,只有认证用户可以访问, 否则只能读取
REST_FRAMEWORK = {
#2.权限配置(全局): 顺序靠上的严格
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 认证用户可以访问, 否则只能读取
],
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3.2.2 测试自定义权限
功能
注:自定义权限会覆盖settings.py中配置的全局权限
1.自定义权限(
其实应该写到一个单独的文件内进行公用,这里先写到这里进行测试
)
# 自定义权限(局部)
class MyPermission(BasePermission):
# has_permission 是用户对这个视图有没有 GET POST PUT PATCH DELETE 权限的分别判断
def has_permission(self, request, view):
print('has_perm')
# print(view.kwargs.get("pk"), request.user.id)
"""判断用户对模型有没有访问权"""
# 任何用户对使用此权限类的视图都有访问权限
if request.user.is_superuser:
# 管理员对用户模型有访问权
return True
elif view.kwargs.get('pk') == str(request.user.id):
# 携带的id和用户的id相同时有访问权
return True
return False
# has_object_permission 是用户过了 has_permission 判断有权限以后,再判断这个用户有没有对一个具体的对象有没有操作权限
def has_object_permission(self, request, view, obj):
print('has_object_perm')
"""获取单个数据时,判断用户对某个数据对象是否有访问权限"""
if request.user.id == obj.id:
return True
return False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- 2.
user/viesws.py视图函数中指定当前视图要用的
权限类
class UserViewSet(viewsets.ModelViewSet):
# 2.权限:自定义权限类
permission_classes = (MyPermission,)
1
2
3
2
3
# 3.3 限流
syl/settings.py中配置限流
http://192.168.56.100:8888/user/apiview/
'''修改syl/settings.py配置限速设置'''
REST_FRAMEWORK = {
#3.1 限流策略
'DEFAULT_THROTTLE_RATES': {
'user': '3/hour', # 认证用户每小时10次
'anon': '3/day', # 未认证用户每天
},
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 3.4 序列化
user/serialzers.py
from rest_framework import serializers
from user.models import User
def address_validate(data):
# 独立校验器
# raise serializers.ValidationError('请填写实际地址') # 有错就抛出异常
# 没错就返回数据
return data
class UserSerializer(serializers.ModelSerializer):
# 1.独立校验器:重新设定字段, 替换掉模型中的设定, 重新设定地址的长度为5
address = serializers.CharField(max_length=255, min_length=5, validators=[address_validate])
# 2.单一字段验证, 验证地址,validate_字段名
def validate_address(self, data):
if data == '测试':
raise serializers.ValidationError('请填写实际地址') # 有错就抛出异常
return data # 没错就返回结果
def validate_phone(self, data):
# 不符合手机号格式
# raise serializers.ValidationError('手机号格式不正确')
model = self.root.Meta.model
num = model.objects.filter(phone=data).count()
if num > 0:
raise serializers.ValidationError('手机号已存在')
return data
# 3.所有属性验证器
def validate(self, attrs):
# attrs:{"username":"zhangsan", "phone":"18538752511", ....}
# 所有属性验证器
# self.context 中有request和view上下文
# self.context['view'].action 可以取到动作
# attrs 是需要序列化的数据
# raise serializers.ValidationError('xxx错误') # 有问题报错
return attrs # 没问题返回数据
class Meta:
model = User # 指定表
# fields = ('id', ) # 临时添加字段也需要写在这里
fields = '__all__' # 所有字段
# exclude = ['id'] # 排除 id 字段
read_only_fields = ('id',) # 指定字段为 read_only,
# 扩展address: extra_kwargs = {} # 局部替换某些字段的设定, 或者新增设定
extra_kwargs = {
"address": {
"min_length": 5, # 给地址增加 最小长度限制
"default": '默认测试地址', # 增加默认值
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 3.5 自定义分页
http://192.168.56.100:8888/user/user/?page=1&page_size=1
1
- 1.
user/views.py
中定义自定义分页类
# 分页(局部):自定义分页器 局部
class PageNum(PageNumberPagination):
# 查询字符串中代表每页返回数据数量的参数名, 默认值: None
page_size_query_param = 'page_size'
# 查询字符串中代表页码的参数名, 有默认值: page
# page_query_param = 'page'
# 一页中最多的结果条数
max_page_size = 2
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 2.
user/views.py
视图函数中使用
class UserViewSet(viewsets.ModelViewSet):
# 3.分页:自定义分页器 覆盖全局配置
pagination_class = PageNum
1
2
3
2
3
# 3.6 过滤和排序
- 测试url
#1.过滤:查询 用户名(tom),激活的用户
http://192.168.56.100:8888/user/user/?username=tom&phone=&is_active=true
#2.排序:查询所有用户 用id 反向排序
http://192.168.56.100:8888/user/user/?ordering=-id
1
2
3
4
2
3
4
user/views.py
视图函数中配置过滤和排序字段
class UserViewSet(viewsets.ModelViewSet):
# 5.过滤:指定过滤方法类, 排序方法类, 一个或多个
filter_backends = (DjangoFilterBackend, OrderingFilter) # 同时支持过滤和排序
# 5.1指定排序字段, 不设置, 排序功能不起效
ordering_fields = ('date_joined', 'id') # ?ordering=-id
# 5.2指定过滤字段, 不设置, 过滤功能不起效
filter_fields = ('username', 'phone', 'is_active') # ?username=tom&phone=&is_active=true
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 04.多对多序列化
# -*- coding: utf-8 -*-
from rest_framework import serializers
from course.models import *
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = '__all__' # 所有字段
class SectionsSerializer(serializers.ModelSerializer):
class Meta:
model = Sections
fields = '__all__'
class ChaptersSerializer(serializers.ModelSerializer):
sections = SectionsSerializer(many=True)
class Meta:
model = Chapters
fields = '__all__'
class CourseDeepSerializer(CourseSerializer):
# 字段名名, 必须是模型可以 . 引用到的变量
# Course(). "chapters" 才能作为字段名, 如果是集合, 需要加many=True,
chapters = ChaptersSerializer(many=True)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 05.其他用法
# 5.1 views.py
from rest_framework import viewsets, status
class DAppViewSet(viewsets.ModelViewSet):
serializer_class = DAppSerializer
queryset = DApp.objects.all()
filter_class = DAppFilter
def list(self, *args, **kwargs):
orig_queryset = self.filter_queryset(self.get_queryset())
fav_qs = UserFavoriteProject.objects.filter(user=self.request.user).values_list('project__id', flat=True)
queryset = orig_queryset.exclude(pk__in=fav_qs)
pu_qs = ProjectGroupUser.objects.filter(user=self.request.user).values_list('project__id', flat=True)
qs = queryset.exclude(pk__in=pu_qs).values_list('id', flat=True)
pk_lists = list(fav_qs) + list(pu_qs) + list(qs)
ordering = 'FIELD(`id`, %s)' % ','.join(str(p) for p in pk_lists)
queryset = orig_queryset.filter(pk__in=list(pk_lists)).extra(select={'ordering': ordering}, order_by=('ordering',))
page = self.paginate_queryset(queryset)
result_queryset = queryset
if page is not None:
result_queryset = page
serializer = self.get_serializer(result_queryset, many=True)
if page is not None:
result = self.get_paginated_response(serializer.data)
else:
result = Response(serializer.data)
return result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 5.2 serializers.py
class DAppSerializer(DynamicFieldsSerializerMixin, serializers.ModelSerializer):
name = serializers.CharField(required=True)
git_repo = serializers.CharField(required=True)
project = serializers.SlugRelatedField(slug_field='name', required=True, allow_null=True, queryset=DProject.objects.all())
level = serializers.CharField(required=True)
creator = serializers.SlugRelatedField(slug_field='full_name', required=False, many=False, queryset=User.objects.all())
create_time = serializers.DateTimeField(required=False, read_only=True)
update_time = serializers.DateTimeField(required=False, read_only=True)
is_archived = serializers.BooleanField(required=False)
is_deleted = serializers.BooleanField(required=False)
is_favorite = False
channel_apps = []
class Meta:
model = DApp
fields = ('id', 'name', 'git_repo', 'project', 'creator', 'create_time', 'update_time', 'is_archived', 'is_deleted', 'level')
validators = [
UniqueTogetherValidator(
queryset=DApp.objects.filter(is_deleted=False),
fields=['name', 'project'],
message="该团队下已有同名应用!"
)
]
def create(self, validated_data):
validated_data['creator'] = self.context['request'].user
instance = super(DAppSerializer, self).create(validated_data)
for channel_app in self.channel_apps:
obj = ChannelApp.objects.create(**channel_app)
obj.done_app = instance
obj.save()
AppGroupUser.objects.create(user=self.context['request'].user,app=instance,role='1')
return instance
def update(self, instance, validated_data):
user = self.context['request'].user
if self.is_favorite is True:
UserFavoriteApp.objects.get_or_create(user=user, app=instance)
elif self.is_favorite is False:
favorite = UserFavoriteApp.objects.filter(user=user, app=instance).last()
if favorite:
favorite.delete()
for channel_app in self.channel_apps:
qs = ChannelApp.objects.filter(**channel_app).filter(done_app=instance)
if not qs.exists():
obj = ChannelApp.objects.create(**channel_app)
obj.done_app = instance
obj.save()
return super(DAppSerializer, self).update(instance, validated_data)
def to_internal_value(self, data):
if 'is_favorite' in data:
self.is_favorite = data.pop('is_favorite')
if 'channel_apps' in data:
self.channel_apps = data.pop('channel_apps')
return super(DAppSerializer, self).to_internal_value(data)
def to_representation(self, instance):
result = super(DAppSerializer, self).to_representation(instance)
project = instance.project
# 1.找到所有"团队管理员"
items = ProjectGroupUser.objects.filter(project=project, role='1').values_list("user__full_name", flat=True)
admins = {item.strip() for item in items if item.strip()}
# 2.找到所有"应用管理员"
items = AppGroupUser.objects.filter(app=instance, role='1').values_list("user__full_name", flat=True)
app_admins = {item.strip() for item in items if item.strip()}
admins.update(app_admins)
result['admins'] = list(admins)
# 3.判断是否 "is_favorite"
user = self.context['request'].user
qs = UserFavoriteApp.objects.filter(user=user, app=instance)
result['is_favorite'] = True if qs.exists() else False
# 4.判断是否有"编辑应用"权限
pg = ProjectGroupUser.objects.filter(project=project, user=user, role='1')
ag = AppGroupUser.objects.filter(app=instance, user=user, role='1')
sys_admin = SysRole.objects.filter(user=user,role='1')
result['can_be_updated'] = any([pg.exists(), ag.exists(), sys_admin.exists()])
values = ChannelApp.objects.filter(done_app=instance).values(
"channel", "channel_sys_name", "channel_app_domain", "channel_app_name", "channel_app_type",
"channel_app_language")
result["channel_apps"] = list(values)
result['locked'] = self.get_app_locked(instance)
return result
def get_app_locked(self, instance):
if DeltaInstance.objects.filter(Q(app=instance) & ~Q(status__config_name__in=['success', 'cancel'])):
return True
return False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# 5.3 filters.py
class DAppFilter(FilterSet):
name = CharFilter(lookup_expr="icontains")
is_archived = CaseInsensitiveBooleanFilter()
is_deleted = CaseInsensitiveBooleanFilter()
project = CharFilter(method="filter_project")
exact_name = CharFilter(method="filter_exact_name")
project_id = CharFilter(method="filter_project_id")
class Meta:
model = DApp
fields = ('name', 'is_archived', 'is_deleted', 'project')
def filter_project(self, qs, name, value):
return qs.filter(project__name=value)
def filter_exact_name(self, qs, name, value):
return qs.filter(name=value, is_deleted=False)
def filter_project_id(self, qs, name, value):
user = self.request.user
project_id = value
# 如果是"系统管理员",和团队管理员可以看见所有
if CurrentUserRoles.is_sys_admin(user) or CurrentUserRoles.is_project_admin(user, project_id):
return qs.all()
# 查询当前用户,在project_id这个团队下,角色为应用管理员的所有 应用角色
project_apps = AppGroupUser.objects.filter(app__project_id=project_id, user=user, role='1')
app_ids = [appuser.app.id for appuser in project_apps]
if project_apps:
return qs.filter(id__in=app_ids)
return qs.none()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
上次更新: 2024/3/13 15:35:10