models–serializers-permission-views-urls
1、创建models,
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、创建序列化,
class TestSuitSerializer(serializers.ModelSerializer):
class Meta:
model = TestSuit
exclude = ['u_time', 'is_delete']
validators = [
UniqueTogetherValidator(queryset=model.objects.all(),
fields=['name', 'task'])
]
3、创建权限
class TestSuitPermission(IsSuperUserOrReadOnly):
def has_create_permission(self, request, view, obj):
"""当前用户是否是当前项目的leader 创建测试套件的时候用的是task的id"""
queryset = Task.objects.filter(pk=request.data.get('task'))
return queryset and queryset.first().project.leader == request.user
def has_update_delete_permission(self, request, view, obj):
"""当前用户是否是当前项目的leader"""
return obj.task.project.leader == request.user
3、创建views
class TestSuitViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericViewSet):
“”"
没有继承ModelViewSet,只是没有过度开发,只需要相应的查看list,和创建create接口
“”"
queryset = TestSuit.objects.all()
serializer_class = TestSuitSerializer
permission_classes = [IsAuthenticated, TestSuitPermission]
filterset_fields = (‘task’, )
4、写url
5、调试前端发现添加套件,但是任务没有套件,这是因为task里面没有嵌套testsuit,
在任务序列化,添加
test_suits = TestSuitSerializer(many=True, read_only=True)
把套件序列化放到任务序列化上面