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
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: test_rest_framework.py From django-hashid-field with MIT License | 7 votes |
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: metadata.py From dynamic-rest with MIT License | 7 votes |
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 #3
Source File: test_serializer_method_field.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 6 votes |
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 #4
Source File: test_serializer_integrations.py From django-enum-choices with MIT License | 6 votes |
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 #5
Source File: test_serializer_integrations.py From django-enum-choices with MIT License | 6 votes |
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 #6
Source File: test_serializer_integrations.py From django-enum-choices with MIT License | 6 votes |
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 #7
Source File: tests.py From django-auto-prefetching with MIT License | 6 votes |
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 #8
Source File: serializer.py From py2swagger with MIT License | 6 votes |
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 #9
Source File: admin.py From django-restful-admin with MIT License | 6 votes |
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 #10
Source File: test_mutation.py From graphene-django with MIT License | 6 votes |
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 #11
Source File: test_serializer_method_field.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 6 votes |
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 #12
Source File: test_mutation.py From graphene-django with MIT License | 6 votes |
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 #13
Source File: utils.py From django-parler-rest with Apache License 2.0 | 6 votes |
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 #14
Source File: serializers.py From open-humans with MIT License | 6 votes |
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 #15
Source File: test_rest_framework.py From django-hashid-field with MIT License | 6 votes |
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 #16
Source File: views.py From wagtailmodelchoosers with MIT License | 6 votes |
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 |
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: test_field_converter.py From graphene-django with MIT License | 5 votes |
def test_should_model_convert_field(): class MyModelSerializer(serializers.ModelSerializer): class Meta: model = None fields = "__all__" assert_conversion(MyModelSerializer, graphene.Field, is_input=False)
Example #19
Source File: serializers.py From Project-Dashboard-with-Django with MIT License | 5 votes |
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 #20
Source File: rest_processing.py From scirius with GNU General Public License v3.0 | 5 votes |
def to_internal_value(self, data): from scirius.utils import get_middleware_module options = data.get('options') action = data.get('action') action_options_serializer = get_middleware_module('common').update_processing_filter_action_options_serializer(ACTION_OPTIONS_SERIALIZER) serializer = action_options_serializer.get(action) if serializer: serializer = serializer(data=options, context=self.context) try: serializer.is_valid(raise_exception=True) except serializers.ValidationError as e: raise serializers.ValidationError({'options': [e.detail]}) options = serializer.validated_data else: if options: raise serializers.ValidationError({'options': ['Action "%s" does not accept options.' % action]}) options = {} if not isinstance(serializer, serializers.ModelSerializer): if self.partial: if 'options' in data: data['options'] = options else: data['options'] = options else: self.option_serializer = serializer data.pop('options', None) return super(RuleProcessingFilterSerializer, self).to_internal_value(data)
Example #21
Source File: test_mutation.py From graphene-django with MIT License | 5 votes |
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"
Example #22
Source File: serializer_converter.py From graphene-django with MIT License | 5 votes |
def convert_serializer_field(field, is_input=True, convert_choices_to_enum=True): """ Converts a django rest frameworks field to a graphql field and marks the field as required if we are creating an input type and the field itself is required """ if isinstance(field, serializers.ChoiceField) and not convert_choices_to_enum: graphql_type = graphene.String else: graphql_type = get_graphene_type_from_serializer_field(field) args = [] kwargs = {"description": field.help_text, "required": is_input and field.required} # if it is a tuple or a list it means that we are returning # the graphql type and the child type if isinstance(graphql_type, (list, tuple)): kwargs["of_type"] = graphql_type[1] graphql_type = graphql_type[0] if isinstance(field, serializers.ModelSerializer): if is_input: graphql_type = convert_serializer_to_input_type(field.__class__) else: global_registry = get_global_registry() field_model = field.Meta.model args = [global_registry.get_type_for_model(field_model)] elif isinstance(field, serializers.ListSerializer): field = field.child if is_input: kwargs["of_type"] = convert_serializer_to_input_type(field.__class__) else: del kwargs["of_type"] global_registry = get_global_registry() field_model = field.Meta.model args = [global_registry.get_type_for_model(field_model)] return graphql_type(*args, **kwargs)
Example #23
Source File: __init__.py From django-auto-prefetching with MIT License | 5 votes |
def prefetch(queryset, serializer: Type[ModelSerializer]): select_related, prefetch_related = _prefetch(serializer) try: return queryset.select_related(*select_related).prefetch_related( *prefetch_related ) except FieldError as e: raise ValueError( f"Calculated wrong field in select_related. Do you have a nested serializer for a ForeignKey where " f"you've forgotten to specify many=True? Original error: {e}" )
Example #24
Source File: tests.py From django-auto-prefetching with MIT License | 5 votes |
def test_with_nested_foreign_key(self): class ChildSerializer(ModelSerializer): class Meta: model = DeeplyNestedChildren fields = ["children", "parent"] depth = 1 class ParentSerializer(ModelSerializer): children = ChildSerializer(source="children_set", many=True) class Meta: model = DeeplyNestedParent fields = ["children", "car"] data = _run_test(ParentSerializer, DeeplyNestedParent, sql_queries=3)
Example #25
Source File: test_rest_framework.py From django-rules with MIT License | 5 votes |
def setUp(self): from testapp.models import TestModel class TestModelSerializer(ModelSerializer): class Meta: model = TestModel fields = "__all__" class TestViewSet(AutoPermissionViewSetMixin, ModelViewSet): queryset = TestModel.objects.all() serializer_class = TestModelSerializer permission_type_map = AutoPermissionViewSetMixin.permission_type_map.copy() permission_type_map["custom_detail"] = "add" permission_type_map["custom_nodetail"] = "add" @action(detail=True) def custom_detail(self, request): return Response() @action(detail=False) def custom_nodetail(self, request): return Response() @action(detail=False) def unknown(self, request): return Response() self.model = TestModel self.vs = TestViewSet self.req = APIRequestFactory().get("/") self.req.user = AnonymousUser()
Example #26
Source File: views.py From weixin_server with MIT License | 5 votes |
def get_serializer_class(self): if self.serializer_class is None: class AutoConfigModelSerializer(ModelSerializer): """Serializer class for configuration models.""" class Meta(object): """Meta information for AutoConfigModelSerializer.""" model = self.model self.serializer_class = AutoConfigModelSerializer return self.serializer_class
Example #27
Source File: tests.py From django-auto-prefetching with MIT License | 5 votes |
def test_it_prefetches_foreign_key_when_source_is_changed(self): car = ParentCar.objects.create() parent = DeeplyNestedParent.objects.create(car=car) class CarSerializer(ModelSerializer): car_id = PrimaryKeyRelatedField( source="car", queryset=ParentCar.objects.all() ) class Meta: model = DeeplyNestedParent fields = ["car", "car_id"] depth = 1 _run_test(CarSerializer, DeeplyNestedParent, 1)
Example #28
Source File: test_serializer_integrations.py From django-enum-choices with MIT License | 5 votes |
def test_field_is_deserialized_correctly_when_using_serializer_mixin(self): class Serializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer): class Meta: model = StringEnumeratedModel fields = ('enumeration', ) serializer = self.Serializer(data={'enumeration': 'first'}) serializer.is_valid() result = serializer.validated_data['enumeration'] self.assertEqual(CharTestEnum.FIRST, result)
Example #29
Source File: test_serializer_integrations.py From django-enum-choices with MIT License | 5 votes |
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)
Example #30
Source File: conftest.py From drf-json-api with MIT License | 5 votes |
def CommentSerializer(): from rest_framework import serializers from tests import models class CommentSerializer(serializers.ModelSerializer): class Meta: model = models.Comment return CommentSerializer