Python rest_framework.serializers.ModelSerializer() Examples

The following are 30 code examples of rest_framework.serializers.ModelSerializer(). 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_rest_framework.py    From django-hashid-field with MIT License 7 votes vote down vote up
def test_modelserializer_integerfield(self):
        class ArtistSerializer(serializers.ModelSerializer):
            id = HashidSerializerIntegerField(source_field=Artist._meta.get_field('id'))

            class Meta:
                model = Artist
                fields = ('id', 'name')

        artist = Artist.objects.create(id=256, name="Test Artist")
        orig_id = artist.id
        s = ArtistSerializer(artist)
        self.assertTrue(isinstance(s.data['id'], int))
        self.assertEqual(artist.id.id, s.data['id'])
        s2 = ArtistSerializer(artist, data={'id': 256, 'name': "Test Artist Changed"})
        self.assertTrue(s2.is_valid())
        artist = s2.save()
        self.assertEqual(artist.id, orig_id)
        self.assertEqual(artist.name, "Test Artist Changed") 
Example #2
Source File: serializer.py    From py2swagger with MIT License 6 votes vote down vote up
def _get_name(self):
        """
        :return: Serializer name
        :rtype: str
        """
        serializer = self.serializer

        if inspect.isclass(serializer):
            name = serializer.__name__
        else:
            name = serializer.__class__.__name__

        if name == 'DefaultSerializer' and issubclass(serializer, ModelSerializer):
            model_name = self.serializer.Meta.model.__name__
            name = '{0}Serializer'.format(model_name.strip())
        return name 
Example #3
Source File: test_rest_framework.py    From django-hashid-field with MIT License 6 votes vote down vote up
def test_modelserializer_charfield(self):
        class ArtistSerializer(serializers.ModelSerializer):
            id = HashidSerializerCharField(source_field='tests.Artist.id')

            class Meta:
                model = Artist
                fields = ('id', 'name')

        artist = Artist.objects.create(id=128, name="Test Artist")
        orig_id = artist.id
        s = ArtistSerializer(artist)
        self.assertEqual(Artist._meta.get_field('id').salt, s.fields['id'].hashid_salt)
        self.assertTrue(isinstance(s.data['id'], str))
        self.assertEqual(artist.id.hashid, s.data['id'])
        s2 = ArtistSerializer(artist, data={'id': 128, 'name': "Test Artist Changed"})
        self.assertTrue(s2.is_valid())
        artist = s2.save()
        self.assertEqual(artist.id, orig_id)
        self.assertEqual(artist.name, "Test Artist Changed") 
Example #4
Source File: utils.py    From django-parler-rest with Apache License 2.0 6 votes vote down vote up
def create_translated_fields_serializer(shared_model, meta=None, related_name=None, **fields):
    """
    Create a Rest Framework serializer class for a translated fields model.

    :param shared_model: The shared model.
    :type shared_model: :class:`parler.models.TranslatableModel`
    """
    if not related_name:
        translated_model = shared_model._parler_meta.root_model
    else:
        translated_model = shared_model._parler_meta[related_name].model

    # Define inner Meta class
    if not meta:
        meta = {}
    meta['model'] = translated_model
    meta.setdefault('fields', ['language_code'] + translated_model.get_translated_fields())

    # Define serialize class attributes
    attrs = {}
    attrs.update(fields)
    attrs['Meta'] = type('Meta', (), meta)

    # Dynamically create the serializer class
    return type('{0}Serializer'.format(translated_model.__name__), (serializers.ModelSerializer,), attrs) 
Example #5
Source File: test_serializer_method_field.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_method_name_custom():
    class BlogSerializer(serializers.ModelSerializer):
        one_entry = SerializerMethodResourceRelatedField(
            model=Entry,
            method_name='get_custom_entry'
        )

        class Meta:
            model = Blog
            fields = ['one_entry']

        def get_custom_entry(self, instance):
            return Entry(id=100)

    serializer = BlogSerializer(instance=Blog())
    assert serializer.data['one_entry']['id'] == '100' 
Example #6
Source File: test_serializer_method_field.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_source():
    class BlogSerializer(serializers.ModelSerializer):
        one_entry = SerializerMethodResourceRelatedField(
            model=Entry,
            source='get_custom_entry'
        )

        class Meta:
            model = Blog
            fields = ['one_entry']

        def get_custom_entry(self, instance):
            return Entry(id=100)

    serializer = BlogSerializer(instance=Blog())
    assert serializer.data['one_entry']['id'] == '100' 
Example #7
Source File: metadata.py    From dynamic-rest with MIT License 6 votes vote down vote up
def get_field_info(self, field):
        """Adds `related_to` and `nullable` to the metadata response."""
        field_info = OrderedDict()
        for attr in ('required', 'read_only', 'default', 'label'):
            field_info[attr] = getattr(field, attr)
        if field_info['default'] is empty:
            field_info['default'] = None
        if hasattr(field, 'immutable'):
            field_info['immutable'] = field.immutable
        field_info['nullable'] = field.allow_null
        if hasattr(field, 'choices'):
            field_info['choices'] = [
                {
                    'value': choice_value,
                    'display_name': force_text(choice_name, strings_only=True)
                }
                for choice_value, choice_name in field.choices.items()
            ]
        many = False
        if isinstance(field, DynamicRelationField):
            field = field.serializer
        if isinstance(field, ListSerializer):
            field = field.child
            many = True
        if isinstance(field, ModelSerializer):
            type = 'many' if many else 'one'
            field_info['related_to'] = field.get_plural_name()
        else:
            type = self.label_lookup[field]

        field_info['type'] = type
        return field_info 
Example #8
Source File: admin.py    From django-restful-admin with MIT License 6 votes vote down vote up
def get_urls(self):
        router = DefaultRouter()
        view_sets = []
        for model, view_set in self._registry.items():
            if view_set.queryset is None:
                view_set.queryset = model.objects.all()
            if view_set.serializer_class is None:
                serializer_class = type("%sModelSerializer" % model.__name__, (ModelSerializer,), {
                    "Meta": type("Meta", (object,), {
                        "model": model,
                        "fields": "__all__"
                    }),
                })
                view_set.serializer_class = serializer_class

            view_sets.append(view_set)
            router.register(self.get_model_url(model), view_set, self.get_model_basename(model))

        return router.urls + self._url_patterns 
Example #9
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_after_model_serializer_create(self):
        class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
            class Meta:
                model = StringEnumeratedModel
                fiedls = ('enumeration', )

        current_instance_count = StringEnumeratedModel.objects.count()

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

        instance = serializer.create(serializer.validated_data)

        self.assertEqual(
            current_instance_count + 1,
            StringEnumeratedModel.objects.count()
        )
        self.assertEqual(
            CharTestEnum.FIRST,
            instance.enumeration
        ) 
Example #10
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 #11
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 #12
Source File: tests.py    From django-auto-prefetching with MIT License 6 votes vote down vote up
def test_with_nested_one_to_one(self):
        class ChildSerializer(ModelSerializer):
            class Meta:
                model = DeeplyNestedChild
                fields = ["toy", "parent"]
                depth = 1

        class ParentSerializer(ModelSerializer):
            child = ChildSerializer()

            class Meta:
                model = DeeplyNestedParent
                fields = ["child", "car"]
                depth = 2

        data = _run_test(ParentSerializer, DeeplyNestedParent, sql_queries=2) 
Example #13
Source File: test_mutation.py    From graphene-django with MIT License 6 votes vote down vote up
def test_write_only_field():
    class WriteOnlyFieldModelSerializer(serializers.ModelSerializer):
        password = serializers.CharField(write_only=True)

        class Meta:
            model = MyFakeModelWithPassword
            fields = ["cool_name", "password"]

    class MyMutation(SerializerMutation):
        class Meta:
            serializer_class = WriteOnlyFieldModelSerializer

    result = MyMutation.mutate_and_get_payload(
        None, mock_info(), **{"cool_name": "New Narf", "password": "admin"}
    )

    assert hasattr(result, "cool_name")
    assert not hasattr(
        result, "password"
    ), "'password' is write_only field and shouldn't be visible" 
Example #14
Source File: test_mutation.py    From graphene-django with MIT License 6 votes vote down vote up
def test_read_only_fields():
    class ReadOnlyFieldModelSerializer(serializers.ModelSerializer):
        cool_name = serializers.CharField(read_only=True)

        class Meta:
            model = MyFakeModelWithPassword
            fields = ["cool_name", "password"]

    class MyMutation(SerializerMutation):
        class Meta:
            serializer_class = ReadOnlyFieldModelSerializer

    assert "password" in MyMutation.Input._meta.fields
    assert (
        "cool_name" not in MyMutation.Input._meta.fields
    ), "'cool_name' is read_only field and shouldn't be on arguments" 
Example #15
Source File: serializers.py    From open-humans with MIT License 6 votes vote down vote up
def to_representation(self, instance):
        """
        Rewrite the ModelSerializer to_representation to pass request on to the
        datafile model's download_url function for logging purposes when
        keys are created.
        """
        request = self.context.get("request", None)
        ret = OrderedDict()
        ret["id"] = instance.id
        ret["basename"] = instance.basename
        ret["created"] = instance.created
        ret["datatypes"] = self.get_file_datatypes(instance)
        ret["download_url"] = instance.download_url(request)
        ret["metadata"] = instance.metadata
        ret["source"] = instance.source
        ret["source_project"] = self.get_source_project(instance)

        return ret 
Example #16
Source File: views.py    From wagtailmodelchoosers with MIT License 6 votes vote down vote up
def build_serializer(self, cls, model_name):
        """
        Dynamically build a model serializer class
        """
        class_name = "%sSerializer" % model_name
        meta_class = type('Meta', (), {'model': cls, 'fields': '__all__'})
        serializer_args = {'Meta': meta_class}

        if hasattr(cls, 'content_type'):
            serializer_args.update({
                'content_type': serializers.StringRelatedField()
            })

        model_serializer = type(class_name, (serializers.ModelSerializer,), serializer_args)

        return model_serializer 
Example #17
Source File: test_serializers.py    From drf-haystack with MIT License 6 votes vote down vote up
def setUp(self):
        MockPersonIndex().reindex()

        class MockPersonSerializer(serializers.ModelSerializer):
            class Meta:
                model = MockPerson
                fields = ('id', 'firstname', 'lastname', 'created', 'updated')
                read_only_fields = ('created', 'updated')

        class Serializer1(HaystackSerializerMixin, MockPersonSerializer):
            class Meta(MockPersonSerializer.Meta):
                search_fields = ['text', ]

        class Viewset1(HaystackViewSet):
            serializer_class = Serializer1

        self.serializer1 = Serializer1
        self.viewset1 = Viewset1 
Example #18
Source File: tests.py    From django-rest-serializer-field-permissions with GNU General Public License v3.0 5 votes vote down vote up
def get_album_serializer(self, _tracks):
        class AlbumSerializer(FieldPermissionSerializerMixin, serializers.ModelSerializer):
            tracks = _tracks

            class Meta:
                model = Album
                fields = ('album_name', 'artist', 'tracks')

        return AlbumSerializer 
Example #19
Source File: test_rest_framework.py    From django-hashid-field with MIT License 5 votes vote down vote up
def test_default_modelserializer_field(self):
        class ArtistSerializer(serializers.ModelSerializer):
            class Meta:
                model = Artist
                fields = ('id', 'name')

        with self.assertRaises(exceptions.ImproperlyConfigured):
            ArtistSerializer().fields()  # Fields aren't built until first accessed 
Example #20
Source File: serializers.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def validate(self, attrs):
        email_or_username = attrs.get('email_or_username')
        password = attrs.get('password')

        if email_or_username and password:
            # Check if user sent email
            if validateEmail(email_or_username):
                user_request = get_object_or_404(
                    User,
                    email__iexact=email_or_username,
                )

                email_or_username = user_request.username

            user = authenticate(username=email_or_username, password=password)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise ValidationError(msg)
            else:
                msg = _('Unable to log in with provided credentials.')
                raise ValidationError(msg)
        else:
            msg = _('Must include "email or username" and "password"')
            raise ValidationError(msg)

        attrs['user'] = user
        return attrs


# class ProfileSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = UserProfile
#         exclude = ('user', 'id', 'organization')
# 
Example #21
Source File: serializers.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_profile_picture(self, obj):
        try:
            if obj.user_profile.profile_picture:
                return obj.user_profile.profile_picture.url
        except:
            return None
        return None


# class ProfileUserSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = User
#         exclude = ('last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined', 'groups', 'user_permissions','password')
#         read_only_fields = ('username', 'email', 'last_login', 'date_joined', 'id') 
Example #22
Source File: serializers.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def update(self, instance, validated_data):
        offer = instance
        images = validated_data.pop('images', None)
        if images:
            for image in images:
                pk = image.pop('id', None)
                if pk:
                    if image.get('_removed', False):
                        OfferImage.objects.filter(pk=pk).delete()
                    else:
                        OfferImage.objects.filter(pk=pk).update(**image)
                else:
                    OfferImage.objects.create(offer=offer, **image)
        return serializers.ModelSerializer.update(self, instance, validated_data) 
Example #23
Source File: test_serializer_method_field.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_method_name_default():
    class BlogSerializer(serializers.ModelSerializer):
        one_entry = SerializerMethodResourceRelatedField(model=Entry)

        class Meta:
            model = Blog
            fields = ['one_entry']

        def get_one_entry(self, instance):
            return Entry(id=100)

    serializer = BlogSerializer(instance=Blog())
    assert serializer.data['one_entry']['id'] == '100' 
Example #24
Source File: serializers.py    From InvenTree with MIT License 5 votes vote down vote up
def validate(self, data):
        """ Perform serializer validation.
        In addition to running validators on the serializer fields,
        this class ensures that the underlying model is also validated.
        """
        
        # Run any native validation checks first (may throw an ValidationError)
        data = super(serializers.ModelSerializer, self).validate(data)

        # Now ensure the underlying model is correct
        instance = self.Meta.model(**data)
        instance.clean()

        return data 
Example #25
Source File: serializers.py    From django-rest-encrypted-lookup with GNU General Public License v3.0 5 votes vote down vote up
def get_fields(self):
        ret = serializers.ModelSerializer.get_fields(self)

        if self.lookup_field in ret:
            ret[self.lookup_field] = EncryptedLookupField()

        return ret 
Example #26
Source File: conftest.py    From drf-json-api with MIT License 5 votes vote down vote up
def PersonSerializer():
    from rest_framework import serializers
    from tests import models

    class PersonSerializer(serializers.ModelSerializer):

        class Meta:
            model = models.Person

    return PersonSerializer 
Example #27
Source File: conftest.py    From drf-json-api with MIT License 5 votes vote down vote up
def PostSerializer():
    from rest_framework import serializers
    from tests import models

    class PostSerializer(serializers.ModelSerializer):

        class Meta:
            model = models.Post

    return PostSerializer 
Example #28
Source File: conftest.py    From drf-json-api with MIT License 5 votes vote down vote up
def CommentSerializer():
    from rest_framework import serializers
    from tests import models

    class CommentSerializer(serializers.ModelSerializer):

        class Meta:
            model = models.Comment

    return CommentSerializer 
Example #29
Source File: serializers.py    From Project-Dashboard-with-Django with MIT License 5 votes vote down vote up
def update(self, instance, validated_data):
        """Update a user, setting the password correctly and return it"""
        # remove password
        password = validated_data.pop('password', None)
        user = super().update(instance, validated_data)  # Call ModelSerializer default update function

        if password:
            user.set_password(password)
            user.save()

        return user 
Example #30
Source File: test_serializer_integrations.py    From django-enum-choices with MIT License 5 votes vote down vote up
def test_field_is_serialized_correctly_when_using_serializer_mixin(self):
        class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
            class Meta:
                model = StringEnumeratedModel
                fields = ('enumeration', )

        instance = StringEnumeratedModel.objects.create(
            enumeration=CharTestEnum.FIRST
        )
        serializer = Serializer(instance)
        result = serializer.data['enumeration']

        self.assertEqual('first', result)