这里先写任务应用,再写套件,然后写接口,最后再写请求,
这个是新的应用,要创建子应用,然后添加到settings的注册里面
1、和往常一样先写模型,序列化,权限,视图,urls,
1、创建任务模型
from django.db import models
from utils.models import BaseModel
from apps.projects.models import Project,Module,Environment,Interface
class Task(BaseModel):
name = models.CharField(‘任务名称’, max_length=200, help_text=‘测试任务名称’)
project = models.ForeignKey(Project, verbose_name=‘所属项目’,
on_delete=models.PROTECT, help_text=‘项目id’, related_name=‘tasks’)
modules = models.ManyToManyField(Module, verbose_name=‘负责的模块’, help_text=‘包含模块’)
def __str__(self):
return self.name
class Meta:
db_table = 'tb_task'
verbose_name = '测试任务'
verbose_name_plural = verbose_name
constraints = [
models.UniqueConstraint(fields=['name', 'project'],
name='unique_task_name')
]
class TestSuit(BaseModel):
name = models.CharField('测试套件名称', max_length=200, help_text='测试套件名称')
task = models.ForeignKey(Task, verbose_name='测试任务', on_delete=models.PROTECT,
help_text='测试任务id', related_name='test_suits')
def __str__(self):
return self.name
class Meta:
db_table = 'tb_test_suit'
verbose_name = '测试套件'
verbose_name_plural = verbose_name
constraints = [
models.UniqueConstraint(fields=['name', 'task'],
name='unique_test_suit_name')
]
记得进行数据迁移
2、写序列化
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from rest_framework.exceptions import ValidationError
from apps.testcases.models import Task,TestSuit
from apps.projects.models import Project
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
exclude = ['is_delete', 'u_time']
validators = [
UniqueTogetherValidator(queryset=model.objects.all(),
fields=['name', 'project'])
]
def validate_modules(self, value):
"""选择的模型要是当前项目的模型"""
project_id = self.initial_data.get('project')
queryset = Project.objects.filter(pk=project_id)
if not queryset:
raise ValidationError('id为{}的项目不存在'.format(project_id))
# module表没有关联projects表,需要反向查找用module_set,拿到当前项目的模块 values_list ids 是个元组需要脱壳,
ids = queryset.first().module_set.values_list('id')
# 列表生成式 元组转化成列表
ids = [item[0] for item in ids]
for m in value:
if m.id not in ids:
raise ValidationError('id为{}的模块不在当前项目中'.format(m.id))
return value
3、写权限
from utils.permissions import IsSuperUserOrReadOnly
from apps.projects.models import Project
class TaskPermission(IsSuperUserOrReadOnly):
def has_create_permission(self, request, view, obj):
"""当前用户是否是当前项目的leader"""
pk = request.data.get('project')
queryset = Project.objects.filter(pk=pk)
return queryset and queryset.first().leader == request.user
def has_update_delete_permission(self, request, view, obj):
"""当前用户是否是当前项目的leader"""
return obj.project.leader == request.user
4、写views
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAuthenticated
from testcases.serializers import TaskSerializer
from utils.pagintion import TenItemPerPagePagination
from testcases.permissions import TaskPermission
from apps.testcases.models import Task
class TaskViewSet(ModelViewSet):
serializer_class = TaskSerializer
queryset = Task.objects.all().order_by(‘-c_time’)
# queryset = models.Task.objects.all()
permission_classes = [IsAuthenticated, TaskPermission]
pagination_class = TenItemPerPagePagination
# filterset_field = [‘project’] # 和下面一样
filterset_field = (‘project’,)
def perform_create(self, serializer):
self.check_object_permissions(self.request, None)
super().perform_create(serializer)
5、配置url
from . import views
route = DefaultRouter()
route.register(‘tasks’, views.TaskViewSet)
urlpatterns = route.urls
6、调试