當前位置: 首頁>>代碼示例>>Python>>正文


Python serializers.ListField方法代碼示例

本文整理匯總了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) 
開發者ID:estebistec,項目名稱:drf-compound-fields,代碼行數:6,代碼來源:fields.py

示例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) 
開發者ID:open-cmdb,項目名稱:cmdb,代碼行數:30,代碼來源:initialize.py

示例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()) 
開發者ID:OpenAgricultureFoundation,項目名稱:gro-api,代碼行數:9,代碼來源:serializers.py

示例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 
開發者ID:graphql-python,項目名稱:graphene-django,代碼行數:17,代碼來源:test_field_converter.py

示例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 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:33,代碼來源:test_drf.py

示例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 
開發者ID:umutbozkurt,項目名稱:django-rest-framework-mongoengine,代碼行數:17,代碼來源:serializers.py

示例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) 
開發者ID:rsinger86,項目名稱:drf-typed-views,代碼行數:15,代碼來源:validator_factory.py

示例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 
開發者ID:r4fek,項目名稱:django-cassandra-engine,代碼行數:52,代碼來源:serializers.py

示例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 
開發者ID:umutbozkurt,項目名稱:django-rest-framework-mongoengine,代碼行數:62,代碼來源:serializers.py


注:本文中的rest_framework.serializers.ListField方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。