Alter read_only+default behaviour (#5886)

* Always exclude read_only fields from _writable_fields

* Remove `read_only` from `CreateOnlyDefault` example.
      In this context (without mentioning `save`) now slightly misleading.
This commit is contained in:
Carlton Gibson 2018-03-20 21:09:31 +01:00 committed by GitHub
parent 12569f83c9
commit c2b24f83a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 10 additions and 5 deletions

View File

@ -189,7 +189,6 @@ A default class that can be used to *only set a default argument during create o
It takes a single argument, which is the default value or callable that should be used during create operations.
created_at = serializers.DateTimeField(
read_only=True,
default=serializers.CreateOnlyDefault(timezone.now)
)

View File

@ -367,8 +367,7 @@ class Serializer(BaseSerializer):
@cached_property
def _writable_fields(self):
return [
field for field in self.fields.values()
if (not field.read_only) or (field.default is not empty)
field for field in self.fields.values() if not field.read_only
]
@cached_property

View File

@ -219,10 +219,17 @@ class TestSource:
class TestReadOnly:
def setup(self):
class TestSerializer(serializers.Serializer):
read_only = serializers.ReadOnlyField()
read_only = serializers.ReadOnlyField(default="789")
writable = serializers.IntegerField()
self.Serializer = TestSerializer
def test_writable_fields(self):
"""
Read-only fields should not be writable, even with default ()
"""
serializer = self.Serializer()
assert len(serializer._writable_fields) == 1
def test_validate_read_only(self):
"""
Read-only serializers.should not be included in validation.

View File

@ -513,7 +513,7 @@ class TestCacheSerializerData:
class TestDefaultInclusions:
def setup(self):
class ExampleSerializer(serializers.Serializer):
char = serializers.CharField(read_only=True, default='abc')
char = serializers.CharField(default='abc')
integer = serializers.IntegerField()
self.Serializer = ExampleSerializer