2023-07-21 10:21:24 +00:00
|
|
|
|
import sys
|
|
|
|
|
from collections import defaultdict, OrderedDict
|
2019-07-02 09:51:50 +00:00
|
|
|
|
|
2023-07-21 10:21:24 +00:00
|
|
|
|
if sys.version_info.major >= 3 and sys.version_info.minor >= 10:
|
|
|
|
|
from collections.abc import Iterable
|
|
|
|
|
else:
|
|
|
|
|
from collections import Iterable
|
2024-04-26 06:01:44 +00:00
|
|
|
|
from django.conf import settings
|
2019-08-12 09:05:01 +00:00
|
|
|
|
from django.core.exceptions import ObjectDoesNotExist
|
2022-12-07 10:58:57 +00:00
|
|
|
|
from django.db.models import NOT_PROVIDED
|
2023-12-05 03:16:34 +00:00
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
2022-09-26 02:43:18 +00:00
|
|
|
|
from rest_framework import serializers
|
2019-07-02 09:51:50 +00:00
|
|
|
|
from rest_framework.exceptions import ValidationError
|
2019-09-11 06:40:09 +00:00
|
|
|
|
from rest_framework.fields import SkipField, empty
|
2022-12-07 10:58:57 +00:00
|
|
|
|
from rest_framework.settings import api_settings
|
|
|
|
|
from rest_framework.utils import html
|
2022-09-23 10:59:19 +00:00
|
|
|
|
|
2023-02-07 08:21:26 +00:00
|
|
|
|
from common.db.fields import EncryptMixin
|
2024-05-27 03:07:36 +00:00
|
|
|
|
from common.serializers.fields import (
|
|
|
|
|
EncryptedField,
|
|
|
|
|
LabeledChoiceField,
|
|
|
|
|
ObjectRelatedField,
|
|
|
|
|
LabelRelatedField,
|
|
|
|
|
)
|
2022-09-23 10:59:19 +00:00
|
|
|
|
|
|
|
|
|
__all__ = [
|
2024-05-27 03:07:36 +00:00
|
|
|
|
"BulkSerializerMixin",
|
|
|
|
|
"BulkListSerializerMixin",
|
|
|
|
|
"CommonSerializerMixin",
|
|
|
|
|
"CommonBulkSerializerMixin",
|
|
|
|
|
"SecretReadableMixin",
|
|
|
|
|
"CommonModelSerializer",
|
|
|
|
|
"CommonBulkModelSerializer",
|
|
|
|
|
"ResourceLabelsMixin",
|
2022-09-23 10:59:19 +00:00
|
|
|
|
]
|
2019-07-02 09:51:50 +00:00
|
|
|
|
|
|
|
|
|
|
2022-09-26 02:43:18 +00:00
|
|
|
|
class SecretReadableMixin(serializers.Serializer):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
"""加密字段 (EncryptedField) 可读性"""
|
2022-09-26 02:43:18 +00:00
|
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super(SecretReadableMixin, self).__init__(*args, **kwargs)
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if not hasattr(self, "Meta") or not hasattr(self.Meta, "extra_kwargs"):
|
2022-09-26 02:43:18 +00:00
|
|
|
|
return
|
|
|
|
|
extra_kwargs = self.Meta.extra_kwargs
|
|
|
|
|
for field_name, serializer_field in self.fields.items():
|
|
|
|
|
if not isinstance(serializer_field, EncryptedField):
|
|
|
|
|
continue
|
|
|
|
|
if field_name not in extra_kwargs:
|
|
|
|
|
continue
|
|
|
|
|
field_extra_kwargs = extra_kwargs[field_name]
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if "write_only" not in field_extra_kwargs:
|
2022-09-26 02:43:18 +00:00
|
|
|
|
continue
|
|
|
|
|
serializer_field.write_only = field_extra_kwargs['write_only']
|
2024-05-14 05:04:11 +00:00
|
|
|
|
self.remove_spec_info_field()
|
|
|
|
|
|
|
|
|
|
def remove_spec_info_field(self):
|
|
|
|
|
request = self.context.get('request')
|
|
|
|
|
if not request:
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
_format = request.query_params.get('format')
|
|
|
|
|
if _format not in ['csv', 'xlsx']:
|
|
|
|
|
return
|
|
|
|
|
self.fields.pop('spec_info', None)
|
2022-09-26 02:43:18 +00:00
|
|
|
|
|
|
|
|
|
|
2019-07-02 09:51:50 +00:00
|
|
|
|
class BulkSerializerMixin(object):
|
|
|
|
|
"""
|
|
|
|
|
Become rest_framework_bulk not support uuid as a primary key
|
|
|
|
|
so rewrite it. https://github.com/miki725/django-rest-framework-bulk/issues/66
|
|
|
|
|
"""
|
2022-12-07 10:58:57 +00:00
|
|
|
|
|
2019-07-02 09:51:50 +00:00
|
|
|
|
def to_internal_value(self, data):
|
|
|
|
|
from rest_framework_bulk import BulkListSerializer
|
2024-05-27 03:07:36 +00:00
|
|
|
|
|
2019-07-02 09:51:50 +00:00
|
|
|
|
ret = super(BulkSerializerMixin, self).to_internal_value(data)
|
|
|
|
|
|
2024-05-27 03:07:36 +00:00
|
|
|
|
id_attr = getattr(self.Meta, "update_lookup_field", "id")
|
|
|
|
|
if self.context.get("view"):
|
|
|
|
|
request_method = getattr(
|
|
|
|
|
getattr(self.context.get("view"), "request"), "method", ""
|
|
|
|
|
)
|
2019-07-02 09:51:50 +00:00
|
|
|
|
# add update_lookup_field field back to validated data
|
|
|
|
|
# since super by default strips out read-only fields
|
|
|
|
|
# hence id will no longer be present in validated_data
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if all(
|
|
|
|
|
[
|
|
|
|
|
isinstance(self.root, BulkListSerializer),
|
|
|
|
|
id_attr,
|
|
|
|
|
request_method in ("PUT", "PATCH"),
|
|
|
|
|
]
|
|
|
|
|
):
|
|
|
|
|
id_field = self.fields.get("id") or self.fields.get("pk")
|
2019-07-02 09:51:50 +00:00
|
|
|
|
if data.get("id"):
|
|
|
|
|
id_value = id_field.to_internal_value(data.get("id"))
|
|
|
|
|
else:
|
|
|
|
|
id_value = id_field.to_internal_value(data.get("pk"))
|
|
|
|
|
ret[id_attr] = id_value
|
|
|
|
|
return ret
|
|
|
|
|
|
2019-09-11 06:40:09 +00:00
|
|
|
|
def run_validation(self, data=empty):
|
|
|
|
|
"""
|
|
|
|
|
批量创建时,获取到的self.initial_data是list,
|
|
|
|
|
所以想用一个属性来存放当前操作的数据集,在validate_field中使用
|
|
|
|
|
:param data:
|
|
|
|
|
:return:
|
|
|
|
|
"""
|
|
|
|
|
# 只有批量创建的时候,才需要重写 initial_data
|
|
|
|
|
if self.parent:
|
|
|
|
|
self.initial_data = data
|
|
|
|
|
return super().run_validation(data)
|
|
|
|
|
|
2020-07-29 09:04:06 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def many_init(cls, *args, **kwargs):
|
2022-09-26 02:43:18 +00:00
|
|
|
|
from .common import AdaptedBulkListSerializer
|
2024-05-27 03:07:36 +00:00
|
|
|
|
|
|
|
|
|
meta = getattr(cls, "Meta", None)
|
|
|
|
|
assert meta is not None, "Must have `Meta`"
|
|
|
|
|
if not hasattr(meta, "list_serializer_class"):
|
2020-07-29 09:04:06 +00:00
|
|
|
|
meta.list_serializer_class = AdaptedBulkListSerializer
|
|
|
|
|
return super(BulkSerializerMixin, cls).many_init(*args, **kwargs)
|
|
|
|
|
|
2019-07-02 09:51:50 +00:00
|
|
|
|
|
2022-09-26 02:43:18 +00:00
|
|
|
|
class BulkListSerializerMixin:
|
2019-07-02 09:51:50 +00:00
|
|
|
|
"""
|
|
|
|
|
Become rest_framework_bulk doing bulk update raise Exception:
|
|
|
|
|
'QuerySet' object has no attribute 'pk' when doing bulk update
|
|
|
|
|
so rewrite it .
|
|
|
|
|
https://github.com/miki725/django-rest-framework-bulk/issues/68
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def to_internal_value(self, data):
|
|
|
|
|
"""
|
|
|
|
|
List of dicts of native values <- List of dicts of primitive datatypes.
|
|
|
|
|
"""
|
2021-02-24 10:19:23 +00:00
|
|
|
|
if self.instance is None:
|
2019-08-14 12:23:02 +00:00
|
|
|
|
return super().to_internal_value(data)
|
|
|
|
|
|
2019-07-02 09:51:50 +00:00
|
|
|
|
if html.is_html_input(data):
|
|
|
|
|
data = html.parse_html_list(data)
|
|
|
|
|
|
|
|
|
|
if not isinstance(data, list):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
message = self.error_messages["not_a_list"].format(
|
2019-07-02 09:51:50 +00:00
|
|
|
|
input_type=type(data).__name__
|
|
|
|
|
)
|
2024-05-27 03:07:36 +00:00
|
|
|
|
raise ValidationError(
|
|
|
|
|
{api_settings.NON_FIELD_ERRORS_KEY: [message]}, code="not_a_list"
|
|
|
|
|
)
|
2019-07-02 09:51:50 +00:00
|
|
|
|
|
|
|
|
|
if not self.allow_empty and len(data) == 0:
|
|
|
|
|
if self.parent and self.partial:
|
|
|
|
|
raise SkipField()
|
|
|
|
|
|
2024-05-27 03:07:36 +00:00
|
|
|
|
message = self.error_messages["empty"]
|
|
|
|
|
raise ValidationError(
|
|
|
|
|
{api_settings.NON_FIELD_ERRORS_KEY: [message]}, code="empty"
|
|
|
|
|
)
|
2019-07-02 09:51:50 +00:00
|
|
|
|
|
|
|
|
|
ret = []
|
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
|
|
for item in data:
|
|
|
|
|
try:
|
|
|
|
|
# prepare child serializer to only handle one instance
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if "id" in item:
|
2019-08-12 09:05:01 +00:00
|
|
|
|
pk = item["id"]
|
2024-05-27 03:07:36 +00:00
|
|
|
|
elif "pk" in item:
|
2019-08-12 09:05:01 +00:00
|
|
|
|
pk = item["pk"]
|
|
|
|
|
else:
|
|
|
|
|
raise ValidationError("id or pk not in data")
|
2023-02-24 06:33:37 +00:00
|
|
|
|
child = self.instance.get(pk=pk)
|
2019-08-12 09:05:01 +00:00
|
|
|
|
self.child.instance = child
|
2019-07-02 09:51:50 +00:00
|
|
|
|
self.child.initial_data = item
|
|
|
|
|
# raw
|
|
|
|
|
validated = self.child.run_validation(item)
|
|
|
|
|
except ValidationError as exc:
|
|
|
|
|
errors.append(exc.detail)
|
2019-08-12 09:05:01 +00:00
|
|
|
|
except ObjectDoesNotExist as e:
|
|
|
|
|
errors.append(e)
|
2019-07-02 09:51:50 +00:00
|
|
|
|
else:
|
|
|
|
|
ret.append(validated)
|
|
|
|
|
errors.append({})
|
|
|
|
|
|
|
|
|
|
if any(errors):
|
|
|
|
|
raise ValidationError(errors)
|
|
|
|
|
|
|
|
|
|
return ret
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
2021-01-17 04:08:21 +00:00
|
|
|
|
def create(self, validated_data):
|
|
|
|
|
ModelClass = self.child.Meta.model
|
2024-05-27 03:07:36 +00:00
|
|
|
|
use_model_bulk_create = getattr(self.child.Meta, "use_model_bulk_create", False)
|
|
|
|
|
model_bulk_create_kwargs = getattr(
|
|
|
|
|
self.child.Meta, "model_bulk_create_kwargs", {}
|
|
|
|
|
)
|
2021-01-17 04:08:21 +00:00
|
|
|
|
|
|
|
|
|
if use_model_bulk_create:
|
2024-05-27 03:07:36 +00:00
|
|
|
|
to_create = [ModelClass(**attrs) for attrs in validated_data]
|
2021-01-17 04:08:21 +00:00
|
|
|
|
objs = ModelClass._default_manager.bulk_create(
|
|
|
|
|
to_create, **model_bulk_create_kwargs
|
|
|
|
|
)
|
|
|
|
|
return objs
|
|
|
|
|
else:
|
|
|
|
|
return super().create(validated_data)
|
|
|
|
|
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
|
|
|
|
class BaseDynamicFieldsPlugin:
|
|
|
|
|
def __init__(self, serializer):
|
|
|
|
|
self.serializer = serializer
|
|
|
|
|
|
|
|
|
|
def can_dynamic(self):
|
|
|
|
|
try:
|
2024-05-27 03:07:36 +00:00
|
|
|
|
request = self.serializer.context["request"]
|
2020-04-23 03:14:02 +00:00
|
|
|
|
method = request.method
|
|
|
|
|
except (AttributeError, TypeError, KeyError):
|
|
|
|
|
# The serializer was not initialized with request context.
|
|
|
|
|
return False
|
|
|
|
|
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if method != "GET":
|
2020-04-23 03:14:02 +00:00
|
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def get_request(self):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
return self.serializer.context["request"]
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
|
|
|
|
def get_query_params(self):
|
|
|
|
|
request = self.get_request()
|
|
|
|
|
try:
|
|
|
|
|
query_params = request.query_params
|
|
|
|
|
except AttributeError:
|
|
|
|
|
# DRF 2
|
2024-05-27 03:07:36 +00:00
|
|
|
|
query_params = getattr(request, "QUERY_PARAMS", request.GET)
|
2020-04-23 03:14:02 +00:00
|
|
|
|
return query_params
|
|
|
|
|
|
|
|
|
|
def get_exclude_field_names(self):
|
|
|
|
|
return set()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class QueryFieldsMixin(BaseDynamicFieldsPlugin):
|
|
|
|
|
# https://github.com/wimglenn/djangorestframework-queryfields/
|
|
|
|
|
|
|
|
|
|
# If using Django filters in the API, these labels mustn't conflict with any model field names.
|
2024-05-27 03:07:36 +00:00
|
|
|
|
include_arg_name = "fields"
|
|
|
|
|
exclude_arg_name = "fields!"
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
|
|
|
|
# Split field names by this string. It doesn't necessarily have to be a single character.
|
|
|
|
|
# Avoid RFC 1738 reserved characters i.e. ';', '/', '?', ':', '@', '=' and '&'
|
2024-05-27 03:07:36 +00:00
|
|
|
|
delimiter = ","
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
|
|
|
|
def get_exclude_field_names(self):
|
|
|
|
|
query_params = self.get_query_params()
|
|
|
|
|
includes = query_params.getlist(self.include_arg_name)
|
2024-05-27 03:07:36 +00:00
|
|
|
|
include_field_names = {
|
|
|
|
|
name for names in includes for name in names.split(self.delimiter) if name
|
|
|
|
|
}
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
|
|
|
|
excludes = query_params.getlist(self.exclude_arg_name)
|
2024-05-27 03:07:36 +00:00
|
|
|
|
exclude_field_names = {
|
|
|
|
|
name for names in excludes for name in names.split(self.delimiter) if name
|
|
|
|
|
}
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
|
|
|
|
if not include_field_names and not exclude_field_names:
|
|
|
|
|
# No user fields filtering was requested, we have nothing to do here.
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
serializer_field_names = set(self.serializer.fields)
|
|
|
|
|
fields_to_drop = serializer_field_names & exclude_field_names
|
|
|
|
|
|
|
|
|
|
if include_field_names:
|
|
|
|
|
fields_to_drop |= serializer_field_names - include_field_names
|
|
|
|
|
return fields_to_drop
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SizedModelFieldsMixin(BaseDynamicFieldsPlugin):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
arg_name = "fields_size"
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
|
|
|
|
def can_dynamic(self):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if not hasattr(self.serializer, "Meta"):
|
2020-04-23 03:14:02 +00:00
|
|
|
|
return False
|
|
|
|
|
can = super().can_dynamic()
|
|
|
|
|
return can
|
|
|
|
|
|
|
|
|
|
def get_exclude_field_names(self):
|
|
|
|
|
query_params = self.get_query_params()
|
|
|
|
|
size = query_params.get(self.arg_name)
|
|
|
|
|
if not size:
|
|
|
|
|
return []
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if size not in ["mini", "small"]:
|
2020-06-01 02:10:28 +00:00
|
|
|
|
return []
|
2024-05-27 03:07:36 +00:00
|
|
|
|
size_fields = getattr(self.serializer.Meta, "fields_{}".format(size), None)
|
2020-04-23 03:14:02 +00:00
|
|
|
|
if not size_fields or not isinstance(size_fields, Iterable):
|
|
|
|
|
return []
|
|
|
|
|
serializer_field_names = set(self.serializer.fields)
|
|
|
|
|
fields_to_drop = serializer_field_names - set(size_fields)
|
|
|
|
|
return fields_to_drop
|
|
|
|
|
|
|
|
|
|
|
2024-04-26 06:01:44 +00:00
|
|
|
|
class XPACKModelFieldsMixin(BaseDynamicFieldsPlugin):
|
|
|
|
|
def get_exclude_field_names(self):
|
|
|
|
|
if settings.XPACK_LICENSE_IS_VALID:
|
|
|
|
|
return set()
|
2024-05-27 03:07:36 +00:00
|
|
|
|
fields_xpack = set(getattr(self.serializer.Meta, "fields_xpack", set()))
|
2024-04-26 06:01:44 +00:00
|
|
|
|
return fields_xpack
|
|
|
|
|
|
|
|
|
|
|
2021-03-02 11:18:25 +00:00
|
|
|
|
class DefaultValueFieldsMixin:
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
self.set_fields_default_value()
|
|
|
|
|
|
|
|
|
|
def set_fields_default_value(self):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if not hasattr(self, "Meta"):
|
2021-03-02 11:18:25 +00:00
|
|
|
|
return
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if not hasattr(self.Meta, "model"):
|
2021-03-02 11:18:25 +00:00
|
|
|
|
return
|
|
|
|
|
model = self.Meta.model
|
2023-02-07 08:21:26 +00:00
|
|
|
|
|
2021-03-02 11:18:25 +00:00
|
|
|
|
for name, serializer_field in self.fields.items():
|
|
|
|
|
if serializer_field.default != empty or serializer_field.required:
|
|
|
|
|
continue
|
|
|
|
|
model_field = getattr(model, name, None)
|
|
|
|
|
if model_field is None:
|
|
|
|
|
continue
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if (
|
|
|
|
|
not hasattr(model_field, "field")
|
|
|
|
|
or not hasattr(model_field.field, "default")
|
|
|
|
|
or model_field.field.default == NOT_PROVIDED
|
|
|
|
|
):
|
2021-03-02 11:18:25 +00:00
|
|
|
|
continue
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if name == "id":
|
2021-03-02 11:18:25 +00:00
|
|
|
|
continue
|
|
|
|
|
default = model_field.field.default
|
|
|
|
|
|
|
|
|
|
if callable(default):
|
|
|
|
|
default = default()
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if default == "":
|
2021-03-02 11:18:25 +00:00
|
|
|
|
continue
|
|
|
|
|
# print(f"Set default value: {name}: {default}")
|
|
|
|
|
serializer_field.default = default
|
|
|
|
|
|
|
|
|
|
|
2020-04-23 03:14:02 +00:00
|
|
|
|
class DynamicFieldsMixin:
|
2021-03-02 11:18:25 +00:00
|
|
|
|
"""
|
|
|
|
|
可以控制显示不同的字段,mini 最少,small 不包含关系
|
|
|
|
|
"""
|
2024-05-27 03:07:36 +00:00
|
|
|
|
|
|
|
|
|
dynamic_fields_plugins = [
|
|
|
|
|
QueryFieldsMixin,
|
|
|
|
|
SizedModelFieldsMixin,
|
|
|
|
|
XPACKModelFieldsMixin,
|
|
|
|
|
]
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
exclude_field_names = set()
|
|
|
|
|
for cls in self.dynamic_fields_plugins:
|
|
|
|
|
plugin = cls(self)
|
|
|
|
|
if not plugin.can_dynamic():
|
|
|
|
|
continue
|
|
|
|
|
exclude_field_names |= set(plugin.get_exclude_field_names())
|
|
|
|
|
|
|
|
|
|
for field in exclude_field_names or []:
|
|
|
|
|
self.fields.pop(field, None)
|
|
|
|
|
|
|
|
|
|
|
2022-12-07 10:58:57 +00:00
|
|
|
|
class RelatedModelSerializerMixin:
|
|
|
|
|
serializer_related_field = ObjectRelatedField
|
|
|
|
|
serializer_choice_field = LabeledChoiceField
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SomeFieldsMixin:
|
2021-07-13 01:07:57 +00:00
|
|
|
|
instance: None
|
|
|
|
|
initial_data: dict
|
2022-09-26 02:43:18 +00:00
|
|
|
|
common_fields = (
|
2024-05-27 03:07:36 +00:00
|
|
|
|
"comment",
|
|
|
|
|
"created_by",
|
|
|
|
|
"updated_by",
|
|
|
|
|
"date_created",
|
|
|
|
|
"date_updated",
|
2022-09-26 02:43:18 +00:00
|
|
|
|
)
|
2024-05-27 03:07:36 +00:00
|
|
|
|
secret_fields = ("password", "token", "secret", "key", "private_key")
|
2021-07-13 01:07:57 +00:00
|
|
|
|
|
|
|
|
|
def get_initial_value(self, attr, default=None):
|
2021-10-09 09:49:23 +00:00
|
|
|
|
value = self.initial_data.get(attr)
|
2021-11-05 08:11:29 +00:00
|
|
|
|
if value is not None:
|
|
|
|
|
return value
|
|
|
|
|
if self.instance:
|
2021-10-09 09:49:23 +00:00
|
|
|
|
value = getattr(self.instance, attr, default)
|
2021-11-05 08:11:29 +00:00
|
|
|
|
return value
|
|
|
|
|
return default
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
2023-02-07 08:21:26 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def order_fields(fields):
|
|
|
|
|
bool_fields = []
|
|
|
|
|
datetime_fields = []
|
2024-02-05 06:13:07 +00:00
|
|
|
|
common_fields = []
|
2023-02-07 08:21:26 +00:00
|
|
|
|
other_fields = []
|
|
|
|
|
|
|
|
|
|
for name, field in fields.items():
|
|
|
|
|
to_add = (name, field)
|
|
|
|
|
if isinstance(field, serializers.BooleanField):
|
|
|
|
|
bool_fields.append(to_add)
|
|
|
|
|
elif isinstance(field, serializers.DateTimeField):
|
|
|
|
|
datetime_fields.append(to_add)
|
2024-05-27 03:07:36 +00:00
|
|
|
|
elif name in ("comment", "created_by", "updated_by"):
|
2024-02-05 06:13:07 +00:00
|
|
|
|
common_fields.append(to_add)
|
2023-02-07 08:21:26 +00:00
|
|
|
|
else:
|
|
|
|
|
other_fields.append(to_add)
|
2024-02-05 06:13:07 +00:00
|
|
|
|
_fields = [*other_fields, *bool_fields, *datetime_fields, *common_fields]
|
2023-02-07 08:21:26 +00:00
|
|
|
|
fields = OrderedDict()
|
|
|
|
|
for name, field in _fields:
|
|
|
|
|
fields[name] = field
|
|
|
|
|
return fields
|
|
|
|
|
|
2022-09-26 02:43:18 +00:00
|
|
|
|
def get_fields(self):
|
|
|
|
|
fields = super().get_fields()
|
2023-02-07 08:21:26 +00:00
|
|
|
|
fields = self.order_fields(fields)
|
|
|
|
|
secret_readable = isinstance(self, SecretReadableMixin)
|
|
|
|
|
|
2022-09-26 02:43:18 +00:00
|
|
|
|
for name, field in fields.items():
|
2024-05-27 03:07:36 +00:00
|
|
|
|
if name == "id":
|
|
|
|
|
field.label = "ID"
|
2023-02-07 08:21:26 +00:00
|
|
|
|
elif isinstance(field, EncryptMixin) and not secret_readable:
|
2022-09-26 02:43:18 +00:00
|
|
|
|
field.write_only = True
|
|
|
|
|
return fields
|
|
|
|
|
|
2020-05-18 06:55:16 +00:00
|
|
|
|
|
2024-05-27 03:07:36 +00:00
|
|
|
|
class CommonSerializerMixin(
|
|
|
|
|
DynamicFieldsMixin,
|
|
|
|
|
RelatedModelSerializerMixin,
|
|
|
|
|
SomeFieldsMixin,
|
|
|
|
|
DefaultValueFieldsMixin,
|
|
|
|
|
):
|
2022-12-07 10:58:57 +00:00
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
|
class CommonModelSerializer(CommonSerializerMixin, serializers.ModelSerializer):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2020-05-18 06:55:16 +00:00
|
|
|
|
class CommonBulkSerializerMixin(BulkSerializerMixin, CommonSerializerMixin):
|
2023-02-02 12:10:48 +00:00
|
|
|
|
_save_kwargs = defaultdict(dict)
|
2023-01-16 11:02:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CommonBulkModelSerializer(CommonBulkSerializerMixin, serializers.ModelSerializer):
|
|
|
|
|
pass
|
2023-12-05 03:16:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ResourceLabelsMixin(serializers.Serializer):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
labels = LabelRelatedField(
|
|
|
|
|
many=True, label=_("Tags"), required=False, allow_null=True, source="res_labels"
|
|
|
|
|
)
|
2023-12-05 03:16:34 +00:00
|
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
labels = validated_data.pop("res_labels", None)
|
2023-12-05 03:16:34 +00:00
|
|
|
|
res = super().update(instance, validated_data)
|
|
|
|
|
if labels is not None:
|
2024-01-17 09:44:11 +00:00
|
|
|
|
instance.res_labels.set(labels, bulk=False)
|
2023-12-05 03:16:34 +00:00
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
|
def create(self, validated_data):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
labels = validated_data.pop("res_labels", None)
|
2023-12-05 03:16:34 +00:00
|
|
|
|
instance = super().create(validated_data)
|
|
|
|
|
if labels is not None:
|
2024-01-17 09:44:11 +00:00
|
|
|
|
instance.res_labels.set(labels, bulk=False)
|
2023-12-05 03:16:34 +00:00
|
|
|
|
return instance
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def setup_eager_loading(cls, queryset):
|
2024-05-27 03:07:36 +00:00
|
|
|
|
return queryset.prefetch_related("labels")
|