本文整理汇总了Python中rest_framework.serializers.ListField方法的典型用法代码示例。如果您正苦于以下问题:Python serializers.ListField方法的具体用法?Python serializers.ListField怎么用?Python serializers.ListField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.serializers
的用法示例。
在下文中一共展示了serializers.ListField方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def __init__(self, child, *args, **kwargs):
super(ListOrItemField, self).__init__(*args, **kwargs)
self.item_field = child
self.list_field = ListField(child=child, *args, **kwargs)
示例2: add_serializer
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def add_serializer(table):
fields = table.fields.all()
attributes = {}
for field in fields:
args = {
"label": field.alias
}
if not field.required:
args["default"] = None
args["allow_null"] = True
if field.type == 3:
args["format"] = "%Y-%m-%dT%H:%M:%S"
elif field.type == 6:
args["protocol"] = "IPv4"
f = FIELD_TYPE_MAP[field.type](**args)
if(field.is_multi):
attributes[field.name] = serializers.ListField(default=[], child=f)
else:
attributes[field.name] = f
# if(field.type == 0):
# attributes["validate_{}".format(field.name)] = empty_none
#创建者拿到视图aQ!
# attributes["S-creator"] = serializers.CharField(read_only=True, default=serializers.CurrentUserDefault())
attributes["S-creation-time"] = serializers.DateTimeField(read_only=True, format="%Y-%m-%dT%H:%M:%S",
default=datetime.datetime.now)
attributes["S-last-modified"] = serializers.CharField(default=None, allow_null=True, read_only=True, label="最后修改人")
serializer = type(table.name, (Serializer, ), attributes)
setattr(app_serializers, table.name, serializer)
示例3: get_resources
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def get_resources(self, obj):
child = serializers.HyperlinkedIdentityField(
view_name=self.resources_view_name
)
field = serializers.ListField(child=child)
field.parent = self
return field.to_representation(obj.resources.all())
示例4: test_should_list_convert_to_list
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def test_should_list_convert_to_list():
class StringListField(serializers.ListField):
child = serializers.CharField()
field_a = assert_conversion(
serializers.ListField,
graphene.List,
child=serializers.IntegerField(min_value=0, max_value=100),
)
assert field_a.of_type == graphene.Int
field_b = assert_conversion(StringListField, graphene.List)
assert field_b.of_type == graphene.String
示例5: __init__
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def __init__(self, allow_extra):
class Model(serializers.Serializer):
id = serializers.IntegerField()
client_name = serializers.CharField(max_length=255, trim_whitespace=False)
sort_index = serializers.FloatField()
# client_email = serializers.EmailField(required=False, allow_null=True)
client_phone = serializers.CharField(max_length=255, trim_whitespace=False, required=False, allow_null=True)
class Location(serializers.Serializer):
latitude = serializers.FloatField(required=False, allow_null=True)
longitude = serializers.FloatField(required=False, allow_null=True)
location = Location(required=False, allow_null=True)
contractor = serializers.IntegerField(required=False, allow_null=True, min_value=0)
upstream_http_referrer = serializers.CharField(
max_length=1023, trim_whitespace=False, required=False, allow_null=True
)
grecaptcha_response = serializers.CharField(min_length=20, max_length=1000, trim_whitespace=False)
last_updated = serializers.DateTimeField(required=False, allow_null=True)
class Skill(serializers.Serializer):
subject = serializers.CharField()
subject_id = serializers.IntegerField()
category = serializers.CharField()
qual_level = serializers.CharField()
qual_level_id = serializers.IntegerField()
qual_level_ranking = serializers.FloatField(default=0)
skills = serializers.ListField(child=Skill())
self.allow_extra = allow_extra # unused
self.serializer = Model
示例6: build_compound_field
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def build_compound_field(self, field_name, model_field, child_field):
if isinstance(model_field, me_fields.ListField):
field_class = drf_fields.ListField
elif isinstance(model_field, me_fields.DictField):
field_class = drfm_fields.DictField
else:
return self.build_unknown_field(field_name, model_field.owner_document)
field_kwargs = get_field_kwargs(field_name, model_field)
field_kwargs.pop('model_field', None)
if child_field is not None:
field_kwargs['child'] = child_field
return field_class, field_kwargs
示例7: make_list_validator
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def make_list_validator(cls, item_type: Any, settings: ParamSettings):
options = {
"min_length": settings.min_length,
"max_length": settings.max_length,
"allow_empty": settings.allow_empty,
"default": settings.default,
}
if item_type is not Any:
options["child"] = ValidatorFactory.make(
item_type, settings.child or ParamSettings()
)
return serializers.ListField(**options)
示例8: build_standard_field
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def build_standard_field(self, field_name, model_field):
"""
Create regular model fields.
"""
field_mapping = ClassLookupDict(self.serializer_field_mapping)
field_class = field_mapping[model_field]
field_kwargs = self.get_field_kwargs(field_name, model_field)
if 'choices' in field_kwargs:
# Fields with choices get coerced into `ChoiceField`
# instead of using their regular typed field.
field_class = self.serializer_choice_field
# Some model fields may introduce kwargs that would not be valid
# for the choice field. We need to strip these out.
# Eg. models.DecimalField(max_digits=3, decimal_places=1,
# choices=DECIMAL_CHOICES)
valid_kwargs = {
'read_only', 'write_only',
'required', 'default', 'initial', 'source',
'label', 'help_text', 'style',
'error_messages', 'validators', 'allow_null', 'allow_blank',
'choices'
}
for key in list(field_kwargs.keys()):
if key not in valid_kwargs:
field_kwargs.pop(key)
if not issubclass(field_class, ModelField):
# `model_field` is only valid for the fallback case of
# `ModelField`, which is used when no other typed field
# matched to the model field.
field_kwargs.pop('model_field', None)
if not issubclass(field_class, CharField) and not \
issubclass(field_class, ChoiceField):
# `allow_blank` is only valid for textual fields.
field_kwargs.pop('allow_blank', None)
if postgres_fields and isinstance(model_field,
postgres_fields.ArrayField):
# Populate the `child` argument on `ListField` instances generated
# for the PostgrSQL specfic `ArrayField`.
child_model_field = model_field.base_field
child_field_class, child_field_kwargs = self.build_standard_field(
'child', child_model_field
)
field_kwargs['child'] = child_field_class(**child_field_kwargs)
return field_class, field_kwargs
示例9: recursive_save
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import ListField [as 别名]
def recursive_save(self, validated_data, instance=None):
"""
Recursively traverses validated_data and creates EmbeddedDocuments
of the appropriate subtype from them.
Returns Mongonengine model instance.
"""
# me_data is an analogue of validated_data, but contains
# mongoengine EmbeddedDocument instances for nested data structures
# instead of OrderedDicts.
#
# For example:
# validated_data = {'id:, "1", 'embed': OrderedDict({'a': 'b'})}
# me_data = {'id': "1", 'embed': <EmbeddedDocument>}
me_data = dict()
for key, value in validated_data.items():
try:
field = self.fields[key]
# for EmbeddedDocumentSerializers, call recursive_save
if isinstance(field, EmbeddedDocumentSerializer):
me_data[key] = field.recursive_save(value) if value is not None else value # issue when the value is none
# same for lists of EmbeddedDocumentSerializers i.e.
# ListField(EmbeddedDocumentField) or EmbeddedDocumentListField
elif ((isinstance(field, serializers.ListSerializer) or
isinstance(field, serializers.ListField)) and
isinstance(field.child, EmbeddedDocumentSerializer)):
me_data[key] = []
for datum in value:
me_data[key].append(field.child.recursive_save(datum))
# same for dicts of EmbeddedDocumentSerializers (or, speaking
# in Mongoengine terms, MapField(EmbeddedDocument(Embed))
elif (isinstance(field, drfm_fields.DictField) and
hasattr(field, "child") and
isinstance(field.child, EmbeddedDocumentSerializer)):
me_data[key] = {}
for datum_key, datum_value in value.items():
me_data[key][datum_key] = field.child.recursive_save(datum_value)
# for regular fields just set value
else:
me_data[key] = value
except KeyError: # this is dynamic data
me_data[key] = value
# create (if needed), save (if needed) and return mongoengine instance
if not instance:
instance = self.Meta.model(**me_data)
else:
for key, value in me_data.items():
setattr(instance, key, value)
if self._saving_instances:
instance.save()
return instance