mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-26 03:23:59 +03:00
Update extra_kwargs on model serializer
Ensures that the 'read_only' and 'required' keys from `extra_kwargs` are retained when present. Closes #3091.
This commit is contained in:
parent
5bb02cc7b9
commit
af08c70242
|
@ -1105,8 +1105,8 @@ class ModelSerializer(Serializer):
|
||||||
if extra_kwargs.get('default') and kwargs.get('required') is False:
|
if extra_kwargs.get('default') and kwargs.get('required') is False:
|
||||||
kwargs.pop('required')
|
kwargs.pop('required')
|
||||||
|
|
||||||
if kwargs.get('read_only', False):
|
if extra_kwargs.get('read_only', kwargs.get('read_only', False)):
|
||||||
extra_kwargs.pop('required', None)
|
extra_kwargs.pop('required', None) # Read only fields should always omit the 'required' argument.
|
||||||
|
|
||||||
kwargs.update(extra_kwargs)
|
kwargs.update(extra_kwargs)
|
||||||
|
|
||||||
|
|
|
@ -235,6 +235,23 @@ class TestRegularFieldMappings(TestCase):
|
||||||
""")
|
""")
|
||||||
self.assertEqual(repr(TestSerializer()), expected)
|
self.assertEqual(repr(TestSerializer()), expected)
|
||||||
|
|
||||||
|
def test_extra_field_kwargs_required(self):
|
||||||
|
"""
|
||||||
|
Ensure `extra_kwargs` are passed to generated fields.
|
||||||
|
"""
|
||||||
|
class TestSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = RegularFieldsModel
|
||||||
|
fields = ('auto_field', 'char_field')
|
||||||
|
extra_kwargs = {'auto_field': {'required': False, 'read_only': False}}
|
||||||
|
|
||||||
|
expected = dedent("""
|
||||||
|
TestSerializer():
|
||||||
|
auto_field = IntegerField(read_only=False, required=False)
|
||||||
|
char_field = CharField(max_length=100)
|
||||||
|
""")
|
||||||
|
self.assertEqual(repr(TestSerializer()), expected)
|
||||||
|
|
||||||
def test_invalid_field(self):
|
def test_invalid_field(self):
|
||||||
"""
|
"""
|
||||||
Field names that do not map to a model field or relationship should
|
Field names that do not map to a model field or relationship should
|
||||||
|
|
Loading…
Reference in New Issue
Block a user