Python rest_framework.serializers.SerializerMethodField() Examples

The following are 9 code examples for showing how to use rest_framework.serializers.SerializerMethodField(). 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
Project: drf-haystack   Author: rhblind   File: serializers.py    License: MIT License 6 votes vote down vote up
def get_fields(self):
        """
        This returns a dictionary containing the top most fields,
        ``dates``, ``fields`` and ``queries``.
        """
        field_mapping = OrderedDict()
        for field, data in self.instance.items():
            field_mapping.update(
                {field: self.facet_dict_field_class(
                    child=self.facet_list_field_class(child=self.facet_field_serializer_class(data)), required=False)}
            )

        if self.serialize_objects is True:
            field_mapping["objects"] = serializers.SerializerMethodField()

        return field_mapping 
Example 2
Project: django-rest-messaging   Author: raphaelgyory   File: compat.py    License: ISC License 5 votes vote down vote up
def compat_serializer_method_field(method_name=None):
    """ method_name changed in DRF > 3. See http://www.django-rest-framework.org/topics/3.0-announcement/#optional-argument-to-serializermethodfield. """
    if DRFVLIST[0] >= 3:
        return serializers.SerializerMethodField()
    else:
        return serializers.SerializerMethodField(method_name=method_name) 
Example 3
Project: kpi   Author: kobotoolbox   File: asset_permission_assignment.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def validate(self, attrs):
        # Because `partial_permissions` is a `SerializerMethodField`,
        # it's read-only, so it's not validated nor added to `validated_data`.
        # We need to do it manually
        self.validate_partial_permissions(attrs)
        return attrs 
Example 4
Project: kpi   Author: kobotoolbox   File: serializer_method_file.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._serializer_method_field = serializers.SerializerMethodField()
        super().__init__(*args, **kwargs) 
Example 5
Project: graphene-django   Author: graphql-python   File: mutation.py    License: MIT License 5 votes vote down vote up
def perform_mutate(cls, serializer, info):
        obj = serializer.save()

        kwargs = {}
        for f, field in serializer.fields.items():
            if not field.write_only:
                if isinstance(field, serializers.SerializerMethodField):
                    kwargs[f] = field.to_representation(obj)
                else:
                    kwargs[f] = field.get_attribute(obj)

        return cls(errors=None, **kwargs) 
Example 6
Project: aries-vcr   Author: bcgov   File: search.py    License: Apache License 2.0 5 votes vote down vote up
def get_fields(self):
        field_mapping = OrderedDict()
        field_mapping["facets"] = SerializerMethodField()
        if self.serialize_objects is True:
            field_mapping["objects"] = SerializerMethodField()
        return field_mapping 
Example 7
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 8
Project: drf-haystack   Author: rhblind   File: test_serializers.py    License: MIT License 4 votes vote down vote up
def setUp(self):
        MockPersonIndex().reindex()
        MockPetIndex().reindex()

        class Serializer1(HaystackSerializer):

            integer_field = serializers.IntegerField()
            city = serializers.SerializerMethodField()

            class Meta:
                index_classes = [MockPersonIndex]
                fields = ["text", "firstname", "lastname", "autocomplete"]

            def get_integer_field(self, instance):
                return 1

            def get_city(self, instance):
                return "Declared overriding field"

        class Serializer2(HaystackSerializer):

            class Meta:
                index_classes = [MockPersonIndex]
                exclude = ["firstname"]

        class Serializer3(HaystackSerializer):

            class Meta:
                index_classes = [MockPersonIndex]
                fields = ["text", "firstname", "lastname", "autocomplete"]
                ignore_fields = ["autocomplete"]

        class Serializer7(HaystackSerializer):

            class Meta:
                index_classes = [MockPetIndex]

        class ViewSet1(HaystackViewSet):
            serializer_class = Serializer1

            class Meta:
                index_models = [MockPerson]

        self.serializer1 = Serializer1
        self.serializer2 = Serializer2
        self.serializer3 = Serializer3
        self.serializer7 = Serializer7
        self.view1 = ViewSet1 
Example 9
Project: drf-haystack   Author: rhblind   File: test_serializers.py    License: MIT License 4 votes vote down vote up
def setUp(self):
        MockPersonIndex().reindex()
        MockPetIndex().reindex()

        class Serializer1(HaystackSerializer):
            """
            Regular multiple index serializer
            """

            class Meta:
                index_classes = [MockPersonIndex, MockPetIndex]
                fields = ["text", "firstname", "lastname", "name", "species", "autocomplete"]

        class Serializer2(HaystackSerializer):
            """
            Multiple index serializer with declared fields
            """
            _MockPersonIndex__hair_color = serializers.SerializerMethodField()
            extra = serializers.SerializerMethodField()

            class Meta:
                index_classes = [MockPersonIndex, MockPetIndex]
                exclude = ["firstname"]

            def get__MockPersonIndex__hair_color(self, instance):
                return "black"

            def get_extra(self, instance):
                return 1

        class Serializer3(HaystackSerializer):
            """
            Multiple index serializer with index aliases
            """

            class Meta:
                index_classes = [MockPersonIndex, MockPetIndex]
                exclude = ["firstname"]
                index_aliases = {
                    'mockapp.MockPersonIndex': 'People'
                }

        class ViewSet1(HaystackViewSet):
            serializer_class = Serializer1

        class ViewSet2(HaystackViewSet):
            serializer_class = Serializer2

        class ViewSet3(HaystackViewSet):
            serializer_class = Serializer3

        self.serializer1 = Serializer1
        self.serializer2 = Serializer2
        self.serializer3 = Serializer3

        self.view1 = ViewSet1
        self.view2 = ViewSet2
        self.view3 = ViewSet3