2019-07-03 14:28:20 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
2023-07-24 03:52:25 +00:00
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
2019-07-03 14:28:20 +00:00
|
|
|
|
from rest_framework import serializers
|
|
|
|
|
from rest_framework.validators import UniqueTogetherValidator
|
|
|
|
|
|
2023-02-02 12:10:48 +00:00
|
|
|
|
from common.serializers import CommonModelSerializer, \
|
2023-01-16 11:02:09 +00:00
|
|
|
|
CommonBulkModelSerializer
|
2023-02-02 12:10:48 +00:00
|
|
|
|
from common.validators import ProjectUniqueValidator
|
2019-07-03 14:28:20 +00:00
|
|
|
|
from ..utils import get_current_org_id_for_serializer
|
|
|
|
|
|
|
|
|
|
__all__ = [
|
2023-01-16 11:02:09 +00:00
|
|
|
|
"OrgResourceSerializerMixin", "BulkOrgResourceModelSerializer",
|
|
|
|
|
"OrgResourceModelSerializerMixin",
|
2019-07-03 14:28:20 +00:00
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
|
class OrgResourceSerializerMixin(serializers.Serializer):
|
2019-07-03 14:28:20 +00:00
|
|
|
|
"""
|
|
|
|
|
通过API批量操作资源时, 自动给每个资源添加所需属性org_id的值为current_org_id
|
|
|
|
|
(同时为serializer.is_valid()对Model的unique_together校验做准备)
|
|
|
|
|
由于HiddenField字段不可读,API获取资产信息时获取不到org_id,
|
|
|
|
|
但是coco需要资产的org_id字段,所以修改为CharField类型
|
|
|
|
|
"""
|
|
|
|
|
org_id = serializers.ReadOnlyField(default=get_current_org_id_for_serializer, label=_("Organization"))
|
|
|
|
|
org_name = serializers.ReadOnlyField(label=_("Org name"))
|
2022-09-07 12:24:48 +00:00
|
|
|
|
add_org_fields = True
|
2019-07-03 14:28:20 +00:00
|
|
|
|
|
|
|
|
|
def get_validators(self):
|
|
|
|
|
_validators = super().get_validators()
|
|
|
|
|
validators = []
|
|
|
|
|
|
|
|
|
|
for v in _validators:
|
2022-10-27 08:26:15 +00:00
|
|
|
|
if isinstance(v, UniqueTogetherValidator) and "org_id" in v.fields:
|
2019-07-03 14:28:20 +00:00
|
|
|
|
v = ProjectUniqueValidator(v.queryset, v.fields)
|
|
|
|
|
validators.append(v)
|
|
|
|
|
return validators
|
|
|
|
|
|
|
|
|
|
def get_field_names(self, declared_fields, info):
|
|
|
|
|
fields = super().get_field_names(declared_fields, info)
|
2022-09-07 12:24:48 +00:00
|
|
|
|
if self.add_org_fields:
|
|
|
|
|
fields.extend(["org_id", "org_name"])
|
2019-07-03 14:28:20 +00:00
|
|
|
|
return fields
|
|
|
|
|
|
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
|
class OrgResourceModelSerializerMixin(OrgResourceSerializerMixin, CommonModelSerializer):
|
2019-07-03 14:28:20 +00:00
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
|
class BulkOrgResourceModelSerializer(OrgResourceSerializerMixin, CommonBulkModelSerializer):
|
2019-07-03 14:28:20 +00:00
|
|
|
|
pass
|