feat: serializer 添加默认值,前端可以调用 (#5666)

perf: 优化默认值

Co-authored-by: ibuler <ibuler@qq.com>
pull/5667/head
fit2bot 4 years ago committed by GitHub
parent a56ac7b34e
commit f548b4bd2b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -3,6 +3,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from collections import OrderedDict from collections import OrderedDict
import datetime
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.http import Http404 from django.http import Http404
@ -21,7 +22,7 @@ class SimpleMetadataWithFilters(SimpleMetadata):
attrs = [ attrs = [
'read_only', 'label', 'help_text', 'read_only', 'label', 'help_text',
'min_length', 'max_length', 'min_length', 'max_length',
'min_value', 'max_value', "write_only" 'min_value', 'max_value', "write_only",
] ]
def determine_actions(self, request, view): def determine_actions(self, request, view):
@ -59,9 +60,10 @@ class SimpleMetadataWithFilters(SimpleMetadata):
field_info['type'] = self.label_lookup[field] field_info['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', False) field_info['required'] = getattr(field, 'required', False)
default = getattr(field, 'default', False) default = getattr(field, 'default', None)
if default and isinstance(default, (str, int)): if default is not None and default != empty:
field_info['default'] = default if isinstance(default, (str, int, bool, datetime.datetime, list)):
field_info['default'] = default
for attr in self.attrs: for attr in self.attrs:
value = getattr(field, attr, None) value = getattr(field, attr, None)

@ -2,7 +2,7 @@
# #
from collections import Iterable from collections import Iterable
from django.db.models import Prefetch, F from django.db.models import Prefetch, F, NOT_PROVIDED
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from rest_framework.utils import html from rest_framework.utils import html
from rest_framework.settings import api_settings from rest_framework.settings import api_settings
@ -228,7 +228,43 @@ class SizedModelFieldsMixin(BaseDynamicFieldsPlugin):
return fields_to_drop return fields_to_drop
class DefaultValueFieldsMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_fields_default_value()
def set_fields_default_value(self):
if not hasattr(self, 'Meta'):
return
if not hasattr(self.Meta, 'model'):
return
model = self.Meta.model
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
if not hasattr(model_field, 'field') \
or not hasattr(model_field.field, 'default') \
or model_field.field.default == NOT_PROVIDED:
continue
if name == 'id':
continue
default = model_field.field.default
if callable(default):
default = default()
if default == '':
continue
# print(f"Set default value: {name}: {default}")
serializer_field.default = default
class DynamicFieldsMixin: class DynamicFieldsMixin:
"""
可以控制显示不同的字段mini 最少small 不包含关系
"""
dynamic_fields_plugins = [QueryFieldsMixin, SizedModelFieldsMixin] dynamic_fields_plugins = [QueryFieldsMixin, SizedModelFieldsMixin]
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -256,7 +292,7 @@ class EagerLoadQuerySetFields:
return queryset return queryset
class CommonSerializerMixin(DynamicFieldsMixin): class CommonSerializerMixin(DynamicFieldsMixin, DefaultValueFieldsMixin):
pass pass

@ -24,15 +24,17 @@ class UserSerializer(CommonBulkSerializerMixin, serializers.ModelSerializer):
(1, CUSTOM_PASSWORD) (1, CUSTOM_PASSWORD)
) )
password_strategy = serializers.ChoiceField( password_strategy = serializers.ChoiceField(
choices=PASSWORD_STRATEGY_CHOICES, required=False, initial=0, choices=PASSWORD_STRATEGY_CHOICES, required=False,
label=_('Password strategy'), write_only=True label=_('Password strategy'), write_only=True, default=0
) )
mfa_level_display = serializers.ReadOnlyField(source='get_mfa_level_display', label=_('MFA level for display')) mfa_level_display = serializers.ReadOnlyField(source='get_mfa_level_display', label=_('MFA level for display'))
login_blocked = serializers.SerializerMethodField(label=_('Login blocked')) login_blocked = serializers.SerializerMethodField(label=_('Login blocked'))
can_update = serializers.SerializerMethodField(label=_('Can update')) can_update = serializers.SerializerMethodField(label=_('Can update'))
can_delete = serializers.SerializerMethodField(label=_('Can delete')) can_delete = serializers.SerializerMethodField(label=_('Can delete'))
org_roles = serializers.ListField(label=_('Organization role name'), allow_null=True, required=False, org_roles = serializers.ListField(
child=serializers.ChoiceField(choices=ORG_ROLE.choices)) label=_('Organization role name'), allow_null=True, required=False,
child=serializers.ChoiceField(choices=ORG_ROLE.choices), default=["User"]
)
key_prefix_block = "_LOGIN_BLOCK_{}" key_prefix_block = "_LOGIN_BLOCK_{}"
class Meta: class Meta:
@ -72,6 +74,7 @@ class UserSerializer(CommonBulkSerializerMixin, serializers.ModelSerializer):
'total_role_display': {'label': _('Total role name')}, 'total_role_display': {'label': _('Total role name')},
'mfa_enabled': {'label': _('MFA enabled')}, 'mfa_enabled': {'label': _('MFA enabled')},
'mfa_force_enabled': {'label': _('MFA force enabled')}, 'mfa_force_enabled': {'label': _('MFA force enabled')},
'role': {'default': "User"},
} }
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):

Loading…
Cancel
Save