Django REST FRAMEWORK swagger(二)model序列化

时间:2022-05-18 02:51:55

基于模型(models)序列化

  • 建立models模型

Django项目中建立针对底层数据库结构化字段的数据模型。
实例参考:

class Cabinet(models.Model): id = models.UUIDField(primary_key=True,auto_created=True, default=uuid.uuid4, editable=False) code = models.CharField(max_length=64, default='',blank=True, verbose_name='机架编号') assetCode = models.CharField(max_length=64, default='',blank=True, verbose_name='机柜号') types = models.CharField(max_length=32, default='',blank=True, verbose_name='机柜类型') uBit = models.IntegerField(default=0, verbose_name='机架U数') electric = models.CharField(max_length=16, default='',blank=True, verbose_name='电流类型') power = models.CharField(max_length=16,null=True,blank=True, default='', verbose_name='电源总功率') powerUse = models.CharField(max_length=16,null=True,blank=True, default='', verbose_name='已用电源功率') roomId = models.UUIDField(max_length=36,null=False,blank=False,verbose_name='所属机房') uUse = JSONField(null=True,verbose_name='已用U数') comment = models.CharField(max_length=256,null=True,blank=True,default='',verbose_name='备注') createTime = models.DateTimeField(auto_now_add=True,verbose_name='创建时间') updateTime = models.DateTimeField(auto_now=True,verbose_name='最后更新时间') creatorId = models.IntegerField(default=0,verbose_name='创建者ID') creatorName = models.CharField(max_length=8,blank=True,default='',verbose_name='创建者') isDelete = models.IntegerField(default=0,verbose_name='是否已删除')

 

  • 基于model的serializers序列化

根据model中的数据字段的类型及默认值和其他相关的属性,在serializsers中进行相关错误验证及入库前属性验证操作。
引用serializers.ModelsSerializer方法进行模型序列化操作。
class CabinetSerializer(serializers.ModelSerializer):    
class Meta:        
        model = Cabinet #指定所以序列化的model模型表
        fields = '__all__' #可以单独指定字段或者采用该方法,一次性包含所有的字段,(fields = ('id','code','assets_code','power','powerUse'))
  • 本次采用view来操作入库和序列号验证

实现create、list、get等方法,我放置到view中实现,验证也是如此。
class CabinetList(generics.ListCreateAPIView):
    """机房信息列表"""
    _status = Q(isDelete=0)
    queryset = Cabinet.objects.filter(_status)  #model中查询所有的数据,带入条件进行查询
    serializer_class = CabinetSerializer #此处进行序列号操作
     
    # 以上queryset和serializer两条语句可以完成普通的reset framework查询添加和查询操作,由于需要进行实际调整,因此重写了一下方法
 
    def create(self, request, *args, **kwargs):
        code = request.data['code']
        assetCode = request.data['assetCode']
        roomId = request.data['roomId']
        cabinet_ret = Q(assetCode=assetCode) & Q(roomId=roomId) & Q(isDelete=0)
        if Cabinet.objects.filter(cabinet_ret).exists():
            return Response('同机房{}机柜已存在'.format(assetCode),status=status.HTTP_400_BAD_REQUEST)
        if Cabinet.objects.filter(code=code,isDelete=0).exists():
            return Response('机柜资产编号{}已存在'.format(code),status=status.HTTP_400_BAD_REQUEST)
        try:
            Room.objects.get(Q(id=uuid.UUID(roomId)) & Q(isDelete=0))
        except Room.DoesNotExist:
            return Response('机房ID{}不存在'.format(roomId),status=status.HTTP_400_BAD_REQUEST)
        serializer = CabinetSerializer(data=request.data)
        if serializer.is_valid():
            with transaction.atomic():
                serializer.save()
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
    def get_queryset(self):
        roomId = self.request.GET.get('roomId',None)
        assetCode = self.request.GET.get('assetCode',None)
        query = None
        if roomId:
            try:
                uuid.UUID(roomId)
            except Exception as e:
                logger.error(e)
                return status.HTTP_400_BAD_REQUEST
        if not pyutil.is_none(roomId) and not pyutil.is_empty(roomId):
            _roomId = Q(roomId=roomId) & Q(isDelete=0)
            if query is not None:
                query = query & _roomId
            else:
                query = _roomId
        if not pyutil.is_none(assetCode) and not pyutil.is_empty(assetCode):
            assetCode = assetCode.strip()
            _assetCode = Q(assetCode=assetCode) & Q(isDelete=0)
            if query is not None:
                query = query & _assetCode
            else:
                query = _assetCode
        if query is not None:
            if Cabinet.objects.filter(query).exists():
                cabinet = Cabinet.objects.filter(query)
            else:
                cabinet = status.HTTP_404_NOT_FOUND
        else:
            if Cabinet.objects.filter(isDelete=0).exists():
                cabinet = Cabinet.objects.filter(isDelete=0)
            else:
                cabinet = status.HTTP_404_NOT_FOUND
        return cabinet
 
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        if queryset == status.HTTP_404_NOT_FOUND:
            queryset = []
        elif queryset == status.HTTP_400_BAD_REQUEST:
            return Response('机房Id格式不正确,不属于UUID格式', status=status.HTTP_400_BAD_REQUEST)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page,many=True)
            return self.get_paginated_response(serializer.data)
        serializer = CabinetSerializer(queryset, many=True)
        return Response(serializer.data,status=status.HTTP_200_OK)

 

本次采用model中普通序列化操作(接下来的章节中继续推出。。。)
GET /assets/cabinet/list/
HTTP 200 OKAllow: GET, POST, HEAD, OPTIONSContent-Type: application/jsonVary: Accept{
    "count": 6,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": "4a7ff0ee-e939-4db9-9f0f-5eebfb303959",
            "code": "IDC-622",
            "assetCode": "A442",
            "types": "业务柜",
            "uBit": 42,
            "electric": "直流",
            "power": "3KW",
            "powerUse": "1",
            "roomId": "e3deb067-63d1-4bb8-8cb4-d95c9479533f",
            "uUse": "[6, 7, 8, 30, 31, 32, 33, 34, 35, 36, 37, 9, 10, 1, 2, 3, 4, 46, 47, 48, 49, 50, 38, 39, 60, 61, 62, 63]",
            "comment": "",
            "createTime": "2018-05-11T16:20:19.749532",
            "updateTime": "2018-05-25T15:12:15.555063",
            "creatorId": 0,
            "creatorName": "",
            "isDelete": 0
        },
        {
            "id": "6363cae7-23f3-404b-8099-c1e4a4844a2d",
            "code": "IDC-6",
            "assetCode": "A44",
            "types": "业务柜",
            "uBit": 42,
            "electric": "直流",
            "power": "3KW",
            "powerUse": "1",
            "roomId": "e3deb067-63d1-4bb8-8cb4-d95c9479533f",
            "uUse": "[1, 2, 3, 4, 5, 6, 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, 41, 42, 36, 37, 38, 56, 57]",
            "comment": "",
            "createTime": "2018-05-11T15:45:42.682395",
            "updateTime": "2018-05-23T17:27:21.756329",
            "creatorId": 0,
            "creatorName": "",
            "isDelete": 0
        },
        {
            "id": "648c9f0b-1073-4c68-9b14-3f0e0b096aa1",
            "code": "IDC-5",
            "assetCode": "A12",
            "types": "业务柜",
            "uBit": 42,
            "electric": "直流",
            "power": "3KW",
            "powerUse": "1",
            "roomId": "e3deb067-63d1-4bb8-8cb4-d95c9479533f",
            "uUse": {},
            "comment": "",
            "createTime": "2018-05-11T15:43:27.179935",
            "updateTime": "2018-05-11T15:43:27.179964",
            "creatorId": 0,
            "creatorName": "",
            "isDelete": 0
        },
        {
            "id": "8df3e127-a052-4a66-9af7-b441973c6243",
            "code": "IDC-3",
            "assetCode": "A1",
            "types": "业务柜",
            "uBit": 42,
            "electric": "直流",
            "power": "3KW",
            "powerUse": "1",
            "roomId": "e3deb067-63d1-4bb8-8cb4-d95c9479533f",
            "uUse": {},
            "comment": "",
            "createTime": "2018-05-11T15:43:02.928782",
            "updateTime": "2018-05-11T15:43:02.928812",
            "creatorId": 0,
            "creatorName": "",
            "isDelete": 0
        },
        {
            "id": "d135790f-891d-45f1-87e3-e44552b185df",
            "code": "IDC-1",
            "assetCode": "A105",
            "types": "业务柜",
            "uBit": 47,
            "electric": "直流",
            "power": "3KW",
            "powerUse": "1KW",
            "roomId": "69ceede1-9558-422e-a1df-4cedf736a041",
            "uUse": {},
            "comment": "",
            "createTime": "2018-05-11T18:07:01.426919",
            "updateTime": "2018-05-11T18:08:12.372695",
            "creatorId": 0,
            "creatorName": "",
            "isDelete": 0
        },
        {
            "id": "e54fbb3e-2f29-489d-83bc-6f2ae0ece25a",
            "code": "IDC-10",
            "assetCode": "A10",
            "types": "业务柜",
            "uBit": 42,
            "electric": "直流",
            "power": "3KW",
            "powerUse": "1",
            "roomId": "e3deb067-63d1-4bb8-8cb4-d95c9479533f",
            "uUse": {},
            "comment": "",
            "createTime": "2018-05-11T15:42:08.624365",
            "updateTime": "2018-05-11T15:42:08.624400",
            "creatorId": 0,
            "creatorName": "",
            "isDelete": 0
        }
    ]}