forked from AltSchool/dynamic-rest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
drf.py
80 lines (46 loc) · 1.68 KB
/
drf.py
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
from rest_framework import routers, serializers, viewsets
from .models import Group, Permission, User
# DRF
# DRF Serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'name')
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name')
class PermissionSerializer(serializers.ModelSerializer):
class Meta:
model = Permission
fields = ('id', 'name')
class UserWithGroupsSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'name', 'groups')
groups = GroupSerializer(many=True)
class GroupWithPermissionsSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name', 'permissions')
permissions = PermissionSerializer(many=True)
class UserWithAllSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'name', 'groups')
groups = GroupWithPermissionsSerializer(many=True)
# DRF viewsets
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserWithGroupsViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserWithGroupsSerializer
class UserWithAllViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserWithAllSerializer
# DRF routing
router = routers.DefaultRouter()
router.register(r'drf/users', UserWithGroupsViewSet)
router.register(r'drf/users_with_groups', UserWithGroupsViewSet)
router.register(r'drf/users_with_all', UserWithAllViewSet)