相比类视图,视图集封装更加彻底,不在有get,post方法,取而代之的list和create。本节介绍基于DRF的视图集ViewSet和ModelViewSet。
通用代码
Host的模型定义和序列化定义
#model.py
class Host(models.Model):
"""
域名
"""
name = models.CharField(max_length=50, verbose_name="名称")
host = models.CharField(max_length=1024, verbose_name="host地址")
description = models.CharField(max_length=1024, blank=True, null=True, verbose_name="描述")
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name="项目归属", related_name="host_list")
create_time = models.DateTimeField(auto_now_add=True, null=True, verbose_name="创建时间")
#serializer.py
class HostSerializer(serializers.ModelSerializer):
#模型定义的project,但作为外键数据库存储的为project_id
project_id = serializers.IntegerField()
class Meta:
model = models.Host
# __all__会把数据库对应的字段都返回
# 包括id,host的model对应外键的project以project存储和返回,建议显示的标记字段名称
# fields = "__all__"
fields = ["id", "name", "project_id", "description", "host", "create_time"]
ViewSet
示例代码
from django.shortcuts import get_object_or_404
class HostViewSets(viewsets.ViewSet):
permission_classes = [IsAuthenticated]
authentication_classes = [JWTAuthentication]
def list(self, request):
"""
列表获取
"""
queryset = models.Host.objects.all()
serializer = serializers.HostSerializer(queryset, many=True)
return Response(data=serializer.data)
def retrieve(self, request, pk=None):
"""
查询
"""
queryset = models.Host.objects.all()
host = get_object_or_404(queryset, pk=pk)
serializer = serializers.HostSerializer(host)
return Response(data=serializer.data)
def create(self, request):
"""
新建
"""
serializer = serializers.HostSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data)
else:
return Response("fail", status=status.HTTP_400_BAD_REQUEST)
def update(self, request, pk=None):
"""
更新
"""
queryset = models.Host.objects.all()
host = get_object_or_404(queryset, pk=pk)
serializer = serializers.HostSerializer()
rs = serializer.update(host, request.data)
return Response(serializers.HostSerializer(rs).data)
def delete(self, request, pk=None):
"""
删除
"""
queryset = models.Host.objects.all()
host = get_object_or_404(queryset, pk=pk)
host.delete()
return Response(data='scuccess')
ViewSet视图集相比类视图,get替换为list,retrieve;post替换为create;put替换为update;delete还是为delete方法。
get_object_or_404的使用
get_object_or_404检索目标对象,查不到异常404,源码如下
def get_object_or_404(klass, *args, **kwargs):
"""
Use get() to return an object, or raise a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
one object is found.
"""
queryset = _get_queryset(klass)
if not hasattr(queryset, 'get'):
klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
raise ValueError(
"First argument to get_object_or_404() must be a Model, Manager, "
"or QuerySet, not '%s'." % klass__name
)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
传参klass为queryset对象,其他参数为一个模型对象的检索关键字段和值,如
host = get_object_or_404(queryset, pk=pk)
路由配置
viewset的路由与类视图不同,采用路由注册的方式
1.router.register('域名', '视图集合',basename="")
urlpatterns = [ ... ] + router.urls
from django.urls import path
from rest_framework import routers
from . import views
from . import views_clas
router = routers.DefaultRouter(trailing_slash=False)
router.register('host', views.HostViewSets, basename="host")
router.register('project', views.ProjectViewSets, basename="project")
router.register('api', views.ApiViewSets, basename="api")
# viewset的路由配置
router.register('hostviewset', views_clas.HostViewSets, basename="host_view_set")
router.register('hostmodel', views_clas.HostModelViewSet, basename="host_view_set")
app_name = "apitest"
urlpatterns = [
...
] + router.urls
ModelViewSet
我们一个视图集基本上都是针对一个模型进行操作的,那么增删改查操作针对的也就是不同的模型,所以我们可以使用ModelViewSet简化以上的代码。比如以上代码,我们可以写成:
class HostModelViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated]
authentication_classes = [JWTAuthentication]
queryset = models.Host.objects.all()
serializer_class = serializers.HostSerializer
有时候在一个视图中,我们可能还需要增加其他的url,这时候就可以使用@action来实现:
class HostModelViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated]
authentication_classes = [JWTAuthentication]
queryset = models.Host.objects.all()
serializer_class = serializers.HostSerializer
@action(['GET'], detail=False, url_path="jc/(?P<key>\d+)")
def cs(self, request, key=None):
queryset = self.get_queryset()
queryset = queryset.filter(description__contains=key)
serializer = serializers.HostSerializer(queryset, many=True)
return Response(data=serializer.data)
url为:http://127.0.0.1:8000/hostmodel/jc/1
请求结果为:
[
{
"id": 4,
"project_id": 1,
"name": "8001端口",
"host": "http://127.0.0.1:8001",
"description": "41",
"create_time": "2022-04-18T10:52:07.210592+08:00",
"project": 1
},
{
"id": 5,
"project_id": 1,
"name": "8002端口",
"host": "http://127.0.0.1:8002",
"description": "4441",
"create_time": "2022-04-18T10:52:07.210592+08:00",
"project": 1
},
{
"id": 6,
"project_id": 1,
"name": "8003端口",
"host": "http://127.0.0.1:8003",
"description": "232321",
"create_time": "2022-04-18T10:52:07.210592+08:00",
"project": 1
},
{
"id": 12,
"project_id": 2,
"name": "测试host",
"host": "127.0.0.1",
"description": "接口创建的host1",
"create_time": "2022-04-18T14:18:46.422861+08:00",
"project": 2
}
]