當前位置: 首頁>>代碼示例>>Python>>正文


Python serializers.ModelSerializer方法代碼示例

本文整理匯總了Python中rest_framework.serializers.ModelSerializer方法的典型用法代碼示例。如果您正苦於以下問題:Python serializers.ModelSerializer方法的具體用法?Python serializers.ModelSerializer怎麽用?Python serializers.ModelSerializer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rest_framework.serializers的用法示例。


在下文中一共展示了serializers.ModelSerializer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _get_name

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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 
開發者ID:Arello-Mobile,項目名稱:py2swagger,代碼行數:18,代碼來源:serializer.py

示例2: test_modelserializer_charfield

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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") 
開發者ID:nshafer,項目名稱:django-hashid-field,代碼行數:21,代碼來源:test_rest_framework.py

示例3: test_modelserializer_integerfield

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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") 
開發者ID:nshafer,項目名稱:django-hashid-field,代碼行數:20,代碼來源:test_rest_framework.py

示例4: create_translated_fields_serializer

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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) 
開發者ID:django-parler,項目名稱:django-parler-rest,代碼行數:27,代碼來源:utils.py

示例5: test_method_name_custom

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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' 
開發者ID:django-json-api,項目名稱:django-rest-framework-json-api,代碼行數:18,代碼來源:test_serializer_method_field.py

示例6: test_source

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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' 
開發者ID:django-json-api,項目名稱:django-rest-framework-json-api,代碼行數:18,代碼來源:test_serializer_method_field.py

示例7: get_urls

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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 
開發者ID:amirasaran,項目名稱:django-restful-admin,代碼行數:21,代碼來源:admin.py

示例8: test_instance_is_created_successfully_after_model_serializer_create

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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
        ) 
開發者ID:HackSoftware,項目名稱:django-enum-choices,代碼行數:23,代碼來源:test_serializer_integrations.py

示例9: test_instance_is_updated_successfully_after_model_serializer_update

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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
        ) 
開發者ID:HackSoftware,項目名稱:django-enum-choices,代碼行數:22,代碼來源:test_serializer_integrations.py

示例10: test_instance_is_created_successfully_when_using_custom_choice_builder

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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
        ) 
開發者ID:HackSoftware,項目名稱:django-enum-choices,代碼行數:23,代碼來源:test_serializer_integrations.py

示例11: test_with_nested_one_to_one

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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) 
開發者ID:GeeWee,項目名稱:django-auto-prefetching,代碼行數:18,代碼來源:tests.py

示例12: test_write_only_field

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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" 
開發者ID:graphql-python,項目名稱:graphene-django,代碼行數:22,代碼來源:test_mutation.py

示例13: test_write_only_field_using_extra_kwargs

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
def test_write_only_field_using_extra_kwargs():
    class WriteOnlyFieldModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = MyFakeModelWithPassword
            fields = ["cool_name", "password"]
            extra_kwargs = {"password": {"write_only": True}}

    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" 
開發者ID:graphql-python,項目名稱:graphene-django,代碼行數:21,代碼來源:test_mutation.py

示例14: test_read_only_fields

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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" 
開發者ID:graphql-python,項目名稱:graphene-django,代碼行數:18,代碼來源:test_mutation.py

示例15: to_representation

# 需要導入模塊: from rest_framework import serializers [as 別名]
# 或者: from rest_framework.serializers import ModelSerializer [as 別名]
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 
開發者ID:OpenHumans,項目名稱:open-humans,代碼行數:20,代碼來源:serializers.py


注:本文中的rest_framework.serializers.ModelSerializer方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。