Python rest_framework.serializers.BaseSerializer() Examples

The following are 7 code examples for showing how to use rest_framework.serializers.BaseSerializer(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.serializers , or try the search function .

Example 1
def __get_serializer_fields__(self, serializer):
        fields = []

        if hasattr(serializer, 'get_fields'):
            for key, field in serializer.get_fields().items():
                to_many_relation = True if hasattr(field, 'many') else False
                sub_fields = []

                if to_many_relation:
                    sub_fields = self.__get_serializer_fields__(field.child) if isinstance(field, BaseSerializer) else None
                else:
                    sub_fields = self.__get_serializer_fields__(field) if isinstance(field, BaseSerializer) else None

                fields.append({
                    "name": key,
                    "type": str(field.__class__.__name__),
                    "sub_fields": sub_fields,
                    "required": field.required,
                    "to_many_relation": to_many_relation
                })
            # FIXME:
            # Show more attibutes of `field`?

        return fields 
Example 2
Project: pm-trading-db   Author: gnosis   File: serializers.py    License: MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Gets the kwargs passed to the serializer and produces a new data dictionary with:
            address: string
            creation_date_time: datetime
            creation_block: int

        In addition, all parameters contained in kwargs['data']['params'] are re-elaborated and added to
        the final data dictionary
        """
        # Remove those args not compliant with `serializers.BaseSerializer`
        block = kwargs.pop('block', None) # Avoid KeyError in case key is not in dictionary

        if block:
            self.block = block

        super().__init__(*args, **kwargs)

        self.initial_data = self.parse_event_data(kwargs.pop('data')) 
Example 3
Project: django-rest-framework-json-api   Author: django-json-api   File: renderers.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def extract_attributes(cls, fields, resource):
        """
        Builds the `attributes` object of the JSON API resource object.
        """
        data = OrderedDict()
        render_nested_as_attribute = json_api_settings.SERIALIZE_NESTED_SERIALIZERS_AS_ATTRIBUTE
        for field_name, field in iter(fields.items()):
            # ID is always provided in the root of JSON API so remove it from attributes
            if field_name == 'id':
                continue
            # don't output a key for write only fields
            if fields[field_name].write_only:
                continue
            # Skip fields with relations
            if isinstance(
                    field, (relations.RelatedField, relations.ManyRelatedField)
            ):
                continue

            if isinstance(field, BaseSerializer) and not render_nested_as_attribute:
                continue

            # Skip read_only attribute fields when `resource` is an empty
            # serializer. Prevents the "Raw Data" form of the browsable API
            # from rendering `"foo": null` for read only fields
            try:
                resource[field_name]
            except KeyError:
                if fields[field_name].read_only:
                    continue

            data.update({
                field_name: resource.get(field_name)
            })

        return utils.format_field_names(data) 
Example 4
Project: product-definition-center   Author: product-definition-center   File: renderers_serializers.py    License: MIT License 5 votes vote down vote up
def _get_field_type(serializer, field_name, field, include_read_only):
    """
    Try to describe a field type.
    """
    if not include_read_only and hasattr(field, 'writable_doc_format'):
        return _get_type_from_docstring(field.writable_doc_format)

    if hasattr(field, 'doc_format'):
        return _get_type_from_docstring(field.doc_format)

    if isinstance(field, (relations.ManyRelatedField, serializers.ListSerializer)):
        # Many field, recurse on child and make it a list
        if isinstance(field, relations.ManyRelatedField):
            field = field.child_relation
        else:
            field = field.child
        return [_get_field_type(serializer, field_name, field, include_read_only)]

    if field.__class__.__name__ in _SERIALIZER_DEFS:
        return _SERIALIZER_DEFS[field.__class__.__name__]

    if isinstance(field, serializers.SlugRelatedField):
        return _get_details_for_slug(serializer, field_name, field)

    if isinstance(field, serializers.SerializerMethodField):
        # For method fields try to use docstring of the method.
        method_name = field.method_name or 'get_{field_name}'.format(field_name=field_name)
        method = getattr(serializer, method_name, None)
        if method:
            docstring = getattr(method, '__doc__')
            return _get_type_from_docstring(docstring, docstring or 'method')

    if isinstance(field, serializers.BaseSerializer):
        return describe_serializer(field, include_read_only)

    logger = logging.getLogger(__name__)
    logger.error('Undocumented field %s' % field)
    return 'UNKNOWN' 
Example 5
Project: django-rest-framework-recursive   Author: heywbj   File: fields.py    License: ISC License 5 votes vote down vote up
def proxied(self):
        if not self._proxied:
            if self.bind_args:
                field_name, parent = self.bind_args

                if hasattr(parent, 'child') and parent.child is self:
                    # RecursiveField nested inside of a ListField
                    parent_class = parent.parent.__class__
                else:
                    # RecursiveField directly inside a Serializer
                    parent_class = parent.__class__

                assert issubclass(parent_class, BaseSerializer)

                if self.to is None:
                    proxied_class = parent_class
                else:
                    try:
                        module_name, class_name = self.to.rsplit('.', 1)
                    except ValueError:
                        module_name, class_name = parent_class.__module__, self.to

                    try:
                        proxied_class = getattr(
                            importlib.import_module(module_name), class_name)
                    except Exception as e:
                        raise ImportError(
                            'could not locate serializer %s' % self.to, e)

                # Create a new serializer instance and proxy it
                proxied = proxied_class(**self.init_kwargs)
                proxied.bind(field_name, parent)
                self._proxied = proxied
                
        return self._proxied 
Example 6
Project: django-rest-framework-mongoengine   Author: umutbozkurt   File: serializers.py    License: MIT License 5 votes vote down vote up
def raise_errors_on_nested_writes(method_name, serializer, validated_data):
    # *** inherited from DRF 3, altered for EmbeddedDocumentSerializer to pass ***
    assert not any(
        isinstance(field, serializers.BaseSerializer) and
        not isinstance(field, EmbeddedDocumentSerializer) and
        (key in validated_data)
        for key, field in serializer.fields.items()
    ), (
        'The `.{method_name}()` method does not support writable nested'
        'fields by default.\nWrite an explicit `.{method_name}()` method for '
        'serializer `{module}.{class_name}`, or set `read_only=True` on '
        'nested serializer fields.'.format(
            method_name=method_name,
            module=serializer.__class__.__module__,
            class_name=serializer.__class__.__name__
        )
    )

    assert not any(
        '.' in field.source and (key in validated_data) and
        isinstance(validated_data[key], (list, dict))
        for key, field in serializer.fields.items()
    ), (
        'The `.{method_name}()` method does not support writable dotted-source '
        'fields by default.\nWrite an explicit `.{method_name}()` method for '
        'serializer `{module}.{class_name}`, or set `read_only=True` on '
        'dotted-source serializer fields.'.format(
            method_name=method_name,
            module=serializer.__class__.__module__,
            class_name=serializer.__class__.__name__
        )
    ) 
Example 7
Project: py2swagger   Author: Arello-Mobile   File: field.py    License: MIT License 4 votes vote down vote up
def _get_field_object(self, request=False):
        """
        Creates swagger object for field for request or response

        :param request: is this object for request?
        :return: swagger object
        :rtype: OrderedDict
        """
        if isinstance(self._field, BaseSerializer):
            if getattr(self._field, 'many', None):
                result = {
                    'type': 'array',
                    'items': self._serializer_inrospector_class(self._field).build_response_object(),
                }
            else:
                result = self._serializer_inrospector_class(self._field).build_response_object()
        else:
            field_type, data_type, data_format = self._get_field_type(self._field)
            if data_type == 'file' and not request:
                data_type = 'string'
            result = OrderedDict(type=data_type)

            # Retrieve Field metadata
            max_val = getattr(self._field, 'max_value', None)
            min_val = getattr(self._field, 'min_value', None)
            max_length = getattr(self._field, 'max_length', None)
            default = self._get_default_value()
            description = getattr(self._field, 'help_text', '')

            if data_format:
                result['format'] = data_format

            if max_val is not None and data_type in ('integer', 'number'):
                result['minimum'] = min_val

            if max_val is not None and data_type in ('integer', 'number'):
                result['maximum'] = max_val

            if max_length is not None and data_type == 'string':
                result['maxLength'] = max_length

            if description:
                result['description'] = description

            if default is not None:
                result['default'] = default

            if field_type in ['multiple choice', 'choice']:
                if isinstance(self._field.choices, dict):
                    result['enum'] = [k for k in self._field.choices]

                if all(isinstance(item, int) for item in result.get('enum', ['1'])):
                    result['type'] = 'integer'
        return result