本文整理汇总了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
示例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")
示例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")
示例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)
示例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
示例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
)
示例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
)
示例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
)
示例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)
示例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"
示例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"
示例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"
示例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