mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-01-23 15:54:16 +03:00
PK fields should only be read-only if they are an AutoField. Fixes #563
This commit is contained in:
parent
73c4e5c460
commit
d9acec3e6d
|
@ -415,7 +415,7 @@ class ModelSerializer(Serializer):
|
|||
"""
|
||||
Returns a default instance of the pk field.
|
||||
"""
|
||||
return Field()
|
||||
return self.get_field(model_field)
|
||||
|
||||
def get_nested_field(self, model_field):
|
||||
"""
|
||||
|
@ -452,7 +452,7 @@ class ModelSerializer(Serializer):
|
|||
if model_field.null or model_field.blank:
|
||||
kwargs['required'] = False
|
||||
|
||||
if not model_field.editable:
|
||||
if isinstance(model_field, models.AutoField) or not model_field.editable:
|
||||
kwargs['read_only'] = True
|
||||
|
||||
if model_field.has_default():
|
||||
|
@ -468,6 +468,7 @@ class ModelSerializer(Serializer):
|
|||
return ChoiceField(**kwargs)
|
||||
|
||||
field_mapping = {
|
||||
models.AutoField: IntegerField,
|
||||
models.FloatField: FloatField,
|
||||
models.IntegerField: IntegerField,
|
||||
models.PositiveIntegerField: IntegerField,
|
||||
|
|
|
@ -12,11 +12,20 @@ class TimestampedModel(models.Model):
|
|||
updated = models.DateTimeField(auto_now=True)
|
||||
|
||||
|
||||
class CharPrimaryKeyModel(models.Model):
|
||||
id = models.CharField(max_length=20, primary_key=True)
|
||||
|
||||
|
||||
class TimestampedModelSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = TimestampedModel
|
||||
|
||||
|
||||
class CharPrimaryKeyModelSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = CharPrimaryKeyModel
|
||||
|
||||
|
||||
class ReadOnlyFieldTests(TestCase):
|
||||
def test_auto_now_fields_read_only(self):
|
||||
"""
|
||||
|
@ -24,3 +33,11 @@ class ReadOnlyFieldTests(TestCase):
|
|||
"""
|
||||
serializer = TimestampedModelSerializer()
|
||||
self.assertEquals(serializer.fields['added'].read_only, True)
|
||||
|
||||
def test_auto_pk_fields_read_only(self):
|
||||
serializer = TimestampedModelSerializer()
|
||||
self.assertEquals(serializer.fields['id'].read_only, True)
|
||||
|
||||
def test_non_auto_pk_fields_not_read_only(self):
|
||||
serializer = CharPrimaryKeyModelSerializer()
|
||||
self.assertEquals(serializer.fields['id'].read_only, False)
|
||||
|
|
Loading…
Reference in New Issue
Block a user