Python rest_framework.serializers.Serializer() Examples

The following are 30 code examples of rest_framework.serializers.Serializer(). 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: test_serializer_integrations.py    From django-enum-choices with MIT License 6 votes vote down vote up
def test_instance_is_updated_successfully_after_model_serializer_update(self):
        class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
            class Meta:
                model = StringEnumeratedModel
                fiedls = ('enumeration', )

        instance = StringEnumeratedModel.objects.create(
            enumeration=CharTestEnum.FIRST
        )

        serializer = self.Serializer(data={'enumeration': 'second'})
        serializer.is_valid()

        serializer.update(instance, serializer.validated_data)
        instance.refresh_from_db()

        self.assertEqual(
            CharTestEnum.SECOND,
            instance.enumeration
        ) 
Example #2
Source File: serializers.py    From dynamic-rest with MIT License 6 votes vote down vote up
def save(self, *args, **kwargs):
        """Serializer save that address prefetch issues."""
        update = getattr(self, 'instance', None) is not None
        instance = super(
            WithDynamicSerializerMixin,
            self
        ).save(
            *args,
            **kwargs
        )
        view = self._context.get('view')
        if view and update:
            if int(DRF_VERSION[0]) <= 3 and int(DRF_VERSION[1]) < 5:
                # Reload the object on update
                # to get around prefetch cache issues
                # Fixed in DRF in 3.5.0
                instance = self.instance = view.get_object()
        return instance 
Example #3
Source File: test_embedded.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_embedding_custom_nested(self):
        class CustomTestSerializer(Serializer):
            bla = drf_fields.CharField()

        class TestSerializer(DocumentSerializer):
            serializer_embedded_nested = CustomTestSerializer

            class Meta:
                model = NestedEmbeddingDoc
                fields = '__all__'

        expected = dedent("""
            TestSerializer():
                id = ObjectIdField(read_only=True)
                embedded = EmbeddedSerializer(required=False):
                    bla = CharField()
        """)
        assert repr(TestSerializer()) == expected 
Example #4
Source File: generics.py    From djangochannelsrestframework with MIT License 6 votes vote down vote up
def get_serializer_class(self, **kwargs) -> Type[Serializer]:
        """
        Return the class to use for the serializer.
        Defaults to using `self.serializer_class`.

        You may want to override this if you need to provide different
        serializations depending on the incoming request.

        (Eg. admins get full serialization, others get basic serialization)
        """
        assert self.serializer_class is not None, (
            "'%s' should either include a `serializer_class` attribute, "
            "or override the `get_serializer_class()` method." % self.__class__.__name__
        )

        return self.serializer_class 
Example #5
Source File: test_filters.py    From drf-haystack with MIT License 6 votes vote down vote up
def setUp(self):
        MockLocationIndex().reindex()

        class Serializer(HaystackSerializer):

            class Meta:
                index_classes = [MockLocationIndex]
                fields = [
                    "text", "address", "city", "zip_code",
                    "coordinates",
                ]

        class ViewSet(HaystackViewSet):
            index_models = [MockLocation]
            serializer_class = Serializer
            filter_backends = [HaystackGEOSpatialFilter]

        self.view = ViewSet 
Example #6
Source File: serializers.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle_invalid_fields(this, data):
    """Validate incoming data.

    The primary validation being done is ensuring the incoming data only
    contains known fields.

    Args:
        this    (Object): Serializer object
        data    (Dict): data to be validated
    Returns:
        (Dict): Validated data
    Raises:
        (ValidationError): if field inputs are invalid

    """
    unknown_keys = None
    if hasattr(this, "initial_data"):
        unknown_keys = set(this.initial_data.keys()) - set(this.fields.keys())

    if unknown_keys:
        error = {}
        for unknown_key in unknown_keys:
            error[unknown_key] = _("Unsupported parameter or invalid value")
        raise serializers.ValidationError(error)
    return data 
Example #7
Source File: test_serializers.py    From drf-friendly-errors with MIT License 6 votes vote down vote up
def test_char_field_error_content(self):
        # Too long string
        self.data_set['title'] = 'Too Long Title For Defined Serializer'
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['max_length']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title')

        # Empty string
        self.data_set['title'] = ''
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['blank']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title')

        # No data provided
        self.data_set.pop('title')
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['required']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title') 
Example #8
Source File: test_pagination.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pagination_multiple_datatypes(self):
        req = self._get_request('/foo', {'limit': 10, 'offset': 20})
        qs1 = [{'id': i} for i in range(25)]
        qs2 = [{'name': i} for i in range(25)]

        class FakeSerializer1(serializers.Serializer):
            id = serializers.IntegerField()

        class FakeSerializer2(serializers.Serializer):
            name = serializers.IntegerField()

        resp = paginate_results(
            req, (qs1, FakeSerializer1), (qs2, FakeSerializer2))
        assert resp == {
            'count': 50,
            'next': 'http://nxt',
            'previous': 'http://prv',
            'results': (
                [{'id': 20+i} for i in range(5)] +
                [{'name': i} for i in range(5)]
            )
        } 
Example #9
Source File: test_reference.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_custom_nested(self):
        class CustomReferencing(Serializer):
            foo = IntegerField()

        class TestSerializer(DocumentSerializer):
            serializer_reference_nested = CustomReferencing

            class Meta:
                model = ReferencingDoc
                fields = '__all__'
                depth = 1

        expected = dedent("""
            TestSerializer():
                id = ObjectIdField(read_only=True)
                ref = NestedSerializer(read_only=True):
                    foo = IntegerField()
        """)
        assert repr(TestSerializer()) == expected 
Example #10
Source File: response.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, data=None, code=errors.SUCCESS, message=None,
                 template_name=None, headers=None, exception=False, content_type=None):
        super(Response, self).__init__(None, status=HTTP_200_OK)

        if isinstance(data, Serializer):
            msg = (
                'You passed a Serializer instance as data, but '
                'probably meant to pass serialized `.data` or '
                '`.error`. representation.'
            )
            raise AssertionError(msg)

        self.data = {'code': code,
                     'message': message if message else errors.MESSAGES.get(code, errors.UNKNOWN_ERROR),
                     'data': data}
        self.template_name = template_name
        self.exception = exception
        self.content_type = content_type

        if headers:
            for name, value in six.iteritems(headers):
                self[name] = value 
Example #11
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_describe_nested_serializer_many(self):
        class DummyNestedSerializer(serializers.Serializer):
            field = serializers.CharField()

        class DummySerializer(serializers.Serializer):
            top_level = DummyNestedSerializer(many=True)

        instance = DummySerializer()
        result = describe_serializer(instance, True)
        self.assertEqual(_flatten_field_data(result), {
            'top_level': {
                'value': [{
                    'field': {'value': 'string'}
                }]
            }
        }) 
Example #12
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_describe_nested_serializer(self):
        class DummyNestedSerializer(serializers.Serializer):
            field = serializers.CharField()

        class DummySerializer(serializers.Serializer):
            top_level = DummyNestedSerializer()

        instance = DummySerializer()
        result = describe_serializer(instance, True)
        self.assertEqual(_flatten_field_data(result), {
            'top_level': {
                'value': {
                    'field': {'value': 'string'}
                }
            }
        }) 
Example #13
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_describe_field_with_complex_default(self):
        class DummyDefault(object):
            doc_format = 'some string format'

        class DummySerializer(serializers.Serializer):
            field = serializers.CharField(required=False, default=DummyDefault)

        instance = DummySerializer()
        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'field': {
                'tags': 'optional, default="some string format"',
                'value': 'string'
            }
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {'field': {'value': 'string'}}) 
Example #14
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_describe_fields(self):
        class DummySerializer(serializers.Serializer):
            str = serializers.CharField()
            int = serializers.IntegerField()

        instance = DummySerializer()

        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'str': {'value': 'string'},
            'int': {'value': 'int'}
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {
            'str': {'value': 'string'},
            'int': {'value': 'int'}
        }) 
Example #15
Source File: django_app.py    From scout_apm_python with MIT License 6 votes vote down vote up
def drf_router():
    """
    DRF Router as a lazy object because it needs to import User model which
    can't be done until after django.setup()
    """
    from django.contrib.auth.models import User
    from rest_framework import routers
    from rest_framework import serializers
    from rest_framework import viewsets

    class UserSerializer(serializers.Serializer):
        id = serializers.IntegerField(label="ID", read_only=True)
        username = serializers.CharField(max_length=200)

    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer

    router = routers.SimpleRouter()
    router.register(r"users", UserViewSet)
    return router 
Example #16
Source File: utils.py    From serpy with MIT License 6 votes vote down vote up
def benchmark(serializer_fn, repetitions, num_objs=1, data=None):
    total_objs = repetitions * num_objs
    if not isinstance(serializer_fn, type):
        library = 'Marshmallow'
    elif issubclass(serializer_fn, serpy.Serializer):
        library = 'serpy'
    elif issubclass(serializer_fn, rf_serializers.Serializer):
        library = 'Django Rest Framework'
    print('Serializing {} objects using {}'.format(total_objs, library))

    if data is None:
        data = {}

    objs = [Obj(**data) for i in range(num_objs)]
    many = num_objs > 1
    if not many:
        objs = objs[0]

    t1 = time.time()
    for i in range(repetitions):
        serializer_fn(objs, many=many).data
    total_time = time.time() - t1
    print('Total time: {}'.format(total_time))
    print('Objs/s    : {}\n'.format(int(total_objs / total_time)))
    return total_time 
Example #17
Source File: test_serializer_integrations.py    From django-enum-choices with MIT License 6 votes vote down vote up
def test_instance_is_created_successfully_when_using_custom_choice_builder(self):
        class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
            class Meta:
                model = CustomChoiceBuilderEnumeratedModel
                fields = ('enumeration', )

        current_instance_count = CustomChoiceBuilderEnumeratedModel.objects.count()

        serializer = Serializer(data={'enumeration': 'Custom_first'})
        self.assertTrue(serializer.is_valid())

        instance = serializer.create(serializer.validated_data)

        self.assertEqual(
            current_instance_count + 1,
            CustomChoiceBuilderEnumeratedModel.objects.count()
        )
        self.assertEqual(
            CharTestEnum.FIRST,
            instance.enumeration
        ) 
Example #18
Source File: response.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, data=None, code=errors.SUCCESS, message=None,
                 template_name=None, headers=None, exception=False, content_type=None):
        super(Response, self).__init__(None, status=HTTP_200_OK)

        if isinstance(data, Serializer):
            msg = (
                'You passed a Serializer instance as data, but '
                'probably meant to pass serialized `.data` or '
                '`.error`. representation.'
            )
            raise AssertionError(msg)

        self.data = {'code': code,
                     'message': message if message else errors.MESSAGES.get(code, errors.UNKNOWN_ERROR),
                     'data': data}
        self.template_name = template_name
        self.exception = exception
        self.content_type = content_type

        if headers:
            for name, value in six.iteritems(headers):
                self[name] = value 
Example #19
Source File: entities.py    From drf_openapi with MIT License 6 votes vote down vote up
def get_paginator_serializer(self, view, child_serializer_class):
        class BaseFakeListSerializer(serializers.Serializer):
            results = child_serializer_class(many=True)

        class FakePrevNextListSerializer(BaseFakeListSerializer):
            next = URLField()
            previous = URLField()

        # Validate if the view has a pagination_class
        if not (hasattr(view, 'pagination_class')) or view.pagination_class is None:
            return BaseFakeListSerializer

        pager = view.pagination_class
        if hasattr(pager, 'default_pager'):
            # Must be a ProxyPagination
            pager = pager.default_pager

        if issubclass(pager, (PageNumberPagination, LimitOffsetPagination)):
            class FakeListSerializer(FakePrevNextListSerializer):
                count = IntegerField()
            return FakeListSerializer
        elif issubclass(pager, CursorPagination):
            return FakePrevNextListSerializer

        return BaseFakeListSerializer 
Example #20
Source File: test_serializer_integrations.py    From django-enum-choices with MIT License 5 votes vote down vote up
def test_mulitple_field_is_serialized_correctly_when_using_serializer_mixin(self):
        instance = MultipleEnumeratedModel.objects.create(
            enumeration=[CharTestEnum.FIRST, CharTestEnum.SECOND]
        )

        serializer = self.Serializer(instance)
        result = serializer.data['enumeration']

        self.assertEqual(['first', 'second'], result) 
Example #21
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_describe_read_only_field_can_be_excluded(self):
        class DummySerializer(serializers.Serializer):
            field = serializers.CharField(read_only=True)

        instance = DummySerializer()
        result = describe_serializer(instance, False)
        self.assertEqual(result, {}) 
Example #22
Source File: test_api_view_serializer_class_getter.py    From django-rest-registration with MIT License 5 votes vote down vote up
def test_views_serializer_getter_returns_correct_value():
    view_list = [
        v for k, v in vars(views).items() if not k.startswith('_')]
    for view in view_list:
        serializer = view.cls.get_serializer()
        assert isinstance(serializer, Serializer) 
Example #23
Source File: test_reference.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def test_update(self):
        instance = ReferencingDocWithUniqueField.objects.create(ref=self.target)

        class TestSerializer(DocumentSerializer):
            class Meta:
                model = ReferencingDocWithUniqueField
                fields = '__all__'

        new_target = ReferencedDocWithUniqueField.objects.create(
            name="Bar"
        )
        data = {
            'ref': new_target.id
        }

        # Serializer should validate okay.
        serializer = TestSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors

        # Creating the instance, relationship attributes should be set.
        instance = serializer.save()
        assert instance.ref.id == new_target.id

        # Representation should be correct.
        expected = {
            'id': str(instance.id),
            'ref': str(new_target.id)
        }
        assert serializer.data == expected 
Example #24
Source File: test_serializer_integrations.py    From django-enum-choices with MIT License 5 votes vote down vote up
def test_field_can_handle_allow_blank(self):
        # See GH-45
        class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
            class Meta:
                model = BlankNullableEnumeratedModel
                fields = ('enumeration', )

        instance = StringEnumeratedModel.objects.create(
            enumeration=CharTestEnum.FIRST
        )
        serializer = Serializer(instance)
        serializer.data 
Example #25
Source File: initialize.py    From cmdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
def empty_none(self, val):
    if(val == ""):
        return None
    return val

# def remove_empty_str(data):
#     for k, v in data.items():
#         if v == "":
#             data.pop(k)
# def serializer_init(self, instance=None, data=empty, **kwargs):
#     if data is not empty:
#         for k,v in data.items():
#             if(v==""):
#                 data.pop(k)
#     super(Serializer, self).__init__(instance, data, **kwargs) 
Example #26
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 #27
Source File: test_filters.py    From drf-haystack with MIT License 5 votes vote down vote up
def setUp(self):
        MockPersonIndex().reindex()

        class Serializer(HaystackSerializer):

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

        class ViewSet(HaystackViewSet):
            index_models = [MockPerson]
            serializer_class = Serializer
            filter_backends = [HaystackHighlightFilter]

        self.view = ViewSet 
Example #28
Source File: test_reference.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def test_update(self):
        instance = ReferencingDoc.objects.create(ref=self.target)

        class TestSerializer(DocumentSerializer):
            class Meta:
                model = ReferencingDoc
                fields = '__all__'

        new_target = ReferencedDoc.objects.create(
            name="Bar"
        )
        data = {
            'ref': new_target.id
        }

        # Serializer should validate okay.
        serializer = TestSerializer(instance, data=data)
        assert serializer.is_valid(), serializer.errors

        # Creating the instance, relationship attributes should be set.
        instance = serializer.save()
        assert instance.ref.id == new_target.id

        # Representation should be correct.
        expected = {
            'id': str(instance.id),
            'ref': str(new_target.id)
        }
        assert serializer.data == expected 
Example #29
Source File: test_filters.py    From drf-haystack with MIT License 5 votes vote down vote up
def setUp(self):
        MockPersonIndex().reindex()

        class Serializer(HaystackSerializer):

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

        class ViewSet(HaystackViewSet):
            index_models = [MockPerson]
            serializer_class = Serializer
            filter_backends = [HaystackAutocompleteFilter]

        self.view = ViewSet 
Example #30
Source File: test_serializer_integrations.py    From django-enum-choices with MIT License 5 votes vote down vote up
def test_instance_is_updated_successfully_after_model_serializer_update(self):
        instance = MultipleEnumeratedModel.objects.create(
            enumeration=[CharTestEnum.FIRST, CharTestEnum.SECOND]
        )

        serializer = self.Serializer(data={'enumeration': ['first', 'second', 'third']})
        serializer.is_valid()

        serializer.update(instance, serializer.validated_data)
        instance.refresh_from_db()

        self.assertEqual(
            [CharTestEnum.FIRST, CharTestEnum.SECOND, CharTestEnum.THIRD],
            instance.enumeration
        )