Python rest_framework.serializers.ListField() Examples

The following are 9 code examples of rest_framework.serializers.ListField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.serializers , or try the search function .
Example #1
Source File: fields.py    From drf-compound-fields with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, child, *args, **kwargs):
        super(ListOrItemField, self).__init__(*args, **kwargs)
        self.item_field = child
        self.list_field = ListField(child=child, *args, **kwargs) 
Example #2
Source File: serializers.py    From gro-api with GNU General Public License v2.0 5 votes vote down vote up
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()) 
Example #3
Source File: initialize.py    From cmdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example #4
Source File: test_field_converter.py    From graphene-django with MIT License 5 votes vote down vote up
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 
Example #5
Source File: test_drf.py    From pydantic with MIT License 5 votes vote down vote up
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 
Example #6
Source File: serializers.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
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 
Example #7
Source File: validator_factory.py    From drf-typed-views with MIT License 5 votes vote down vote up
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) 
Example #8
Source File: serializers.py    From django-cassandra-engine with BSD 2-Clause "Simplified" License 4 votes vote down vote up
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 
Example #9
Source File: serializers.py    From django-rest-framework-mongoengine with MIT License 4 votes vote down vote up
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