代码
from rest_framework import serializers
from projects.models import Projects
from interfaces.models import Interfaces
class ProjectsModelSerializers(serializers.ModelSerializer):
"""
模型序列化器
"""
class Meta:
model = Projects
exclude = ('update_time', 'is_delete')
read_only_fields = ('id', 'create_time', 'update_time')
class ProjectsNameModelSerializer(serializers.ModelSerializer):
"""
定义获取项目id和name的序列化器
"""
class Meta:
model = Projects
fields = ('id', 'name')
class InterfacesNameModelSerializer(serializers.ModelSerializer):
"""
定义获取接口id和name的序列化器
"""
class Meta:
model = Interfaces
fields = ('id', 'name')
class InterfacesByProjectIdModelSerializer(serializers.ModelSerializer):
"""
定义获取项目下所有接口id和name的序列化器
"""
interfaces = InterfacesNameModelSerializer(many=True, read_only=True)
class Meta:
model = Projects
fields = ('interfaces')
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from projects.models import Projects
from interfaces.models import Interfaces
from projects import serializers
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Projects.objects.all()
serializer_class = serializers.ProjectsModelSerializers
ordering_fields = ['id', 'name', 'leader']
filterset_fields = ['id', 'name', 'leader']
lookup_field = 'id'
@action(methods=['GET'], detail=False, url_name='url_name', url_path='names')
def names(self, request, *args, **kwargs):
"""
获取所有的项目id和名称
访问: http://127.0.0.1:8000/projects/names/
"""
qs = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(qs)
if page is not None:
serializer = self.get_serializer(instance=page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(instance=qs, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@action(methods=['GET'], detail=True)
def interfaces(self, request, id=None):
"""
获取某个项目下所有的接口id和名称
访问:http://127.0.0.1:8000/projects/1/interfaces/
"""
qs = self.get_object()
serializer = self.get_serializer(instance=qs)
return Response(serializer.data)
def get_serializer_class(self):
if self.action == 'names':
return serializers.ProjectsNameModelSerializer
elif self.action == 'interfaces':
return serializers.InterfacesByProjectIdModelSerializer
else:
return self.serializer_class
|