Handle models without .objects manager in ModelSerializer. (#6111)

* Handle models without .objects manager in ModelSerializer.

* Improvements according to review comments.
This commit is contained in:
Oleg 2018-08-06 15:30:43 +03:00 committed by Carlton Gibson
parent 5ad24b0811
commit 8b5e830bce
2 changed files with 23 additions and 4 deletions

View File

@ -937,14 +937,14 @@ class ModelSerializer(Serializer):
many_to_many[field_name] = validated_data.pop(field_name) many_to_many[field_name] = validated_data.pop(field_name)
try: try:
instance = ModelClass.objects.create(**validated_data) instance = ModelClass._default_manager.create(**validated_data)
except TypeError: except TypeError:
tb = traceback.format_exc() tb = traceback.format_exc()
msg = ( msg = (
'Got a `TypeError` when calling `%s.objects.create()`. ' 'Got a `TypeError` when calling `%s._default_manager.create()`. '
'This may be because you have a writable field on the ' 'This may be because you have a writable field on the '
'serializer class that is not a valid argument to ' 'serializer class that is not a valid argument to '
'`%s.objects.create()`. You may need to make the field ' '`%s._default_manager.create()`. You may need to make the field '
'read-only, or override the %s.create() method to handle ' 'read-only, or override the %s.create() method to handle '
'this correctly.\nOriginal exception was:\n %s' % 'this correctly.\nOriginal exception was:\n %s' %
( (

View File

@ -102,6 +102,13 @@ class Issue3674ChildModel(models.Model):
value = models.CharField(primary_key=True, max_length=64) value = models.CharField(primary_key=True, max_length=64)
class Issue6110TestModel(models.Model):
"""Model without .objects manager."""
name = models.CharField(max_length=64)
all_objects = models.Manager()
class UniqueChoiceModel(models.Model): class UniqueChoiceModel(models.Model):
CHOICES = ( CHOICES = (
('choice1', 'choice 1'), ('choice1', 'choice 1'),
@ -126,7 +133,7 @@ class TestModelSerializer(TestCase):
}) })
serializer.is_valid() serializer.is_valid()
msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.' msginitial = 'Got a `TypeError` when calling `OneFieldModel._default_manager.create()`.'
with self.assertRaisesMessage(TypeError, msginitial): with self.assertRaisesMessage(TypeError, msginitial):
serializer.save() serializer.save()
@ -1224,3 +1231,15 @@ class TestFieldSource(TestCase):
""") """)
self.maxDiff = None self.maxDiff = None
self.assertEqual(unicode_repr(TestSerializer()), expected) self.assertEqual(unicode_repr(TestSerializer()), expected)
class Issue6110Test(TestCase):
def test_model_serializer_custom_manager(self):
class TestModelSerializer(serializers.ModelSerializer):
class Meta:
model = Issue6110TestModel
fields = ('name',)
instance = TestModelSerializer().create({'name': 'test_name'})
self.assertEqual(instance.name, 'test_name')