mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-02 20:54:42 +03:00
Merge pull request #2757 from ekiourk/2630/Raise-exception-when-ModelSerializer-used-with-abstract-model
Raise error when ModelSerializer used with abstract model
This commit is contained in:
commit
2394577dc2
|
@ -823,6 +823,10 @@ class ModelSerializer(Serializer):
|
||||||
serializer_class=self.__class__.__name__
|
serializer_class=self.__class__.__name__
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
if model_meta.is_abstract_model(self.Meta.model):
|
||||||
|
raise ValueError(
|
||||||
|
'Cannot use ModelSerializer with Abstract Models.'
|
||||||
|
)
|
||||||
|
|
||||||
declared_fields = copy.deepcopy(self._declared_fields)
|
declared_fields = copy.deepcopy(self._declared_fields)
|
||||||
model = getattr(self.Meta, 'model')
|
model = getattr(self.Meta, 'model')
|
||||||
|
|
|
@ -167,3 +167,10 @@ def _merge_relationships(forward_relations, reverse_relations):
|
||||||
list(forward_relations.items()) +
|
list(forward_relations.items()) +
|
||||||
list(reverse_relations.items())
|
list(reverse_relations.items())
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_abstract_model(model):
|
||||||
|
"""
|
||||||
|
Given a model class, returns a boolean True if it is abstract and False if it is not.
|
||||||
|
"""
|
||||||
|
return hasattr(model, '_meta') and hasattr(model._meta, 'abstract') and model._meta.abstract
|
||||||
|
|
|
@ -94,6 +94,30 @@ class TestModelSerializer(TestCase):
|
||||||
msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.'
|
msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.'
|
||||||
assert str(excinfo.exception).startswith(msginitial)
|
assert str(excinfo.exception).startswith(msginitial)
|
||||||
|
|
||||||
|
def test_abstract_model(self):
|
||||||
|
"""
|
||||||
|
Test that trying to use ModelSerializer with Abstract Models
|
||||||
|
throws a ValueError exception.
|
||||||
|
"""
|
||||||
|
class AbstractModel(models.Model):
|
||||||
|
afield = models.CharField(max_length=255)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
abstract = True
|
||||||
|
|
||||||
|
class TestSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = AbstractModel
|
||||||
|
fields = ('afield',)
|
||||||
|
|
||||||
|
serializer = TestSerializer(data={
|
||||||
|
'afield': 'foo',
|
||||||
|
})
|
||||||
|
with self.assertRaises(ValueError) as excinfo:
|
||||||
|
serializer.is_valid()
|
||||||
|
msginitial = 'Cannot use ModelSerializer with Abstract Models.'
|
||||||
|
assert str(excinfo.exception).startswith(msginitial)
|
||||||
|
|
||||||
|
|
||||||
class TestRegularFieldMappings(TestCase):
|
class TestRegularFieldMappings(TestCase):
|
||||||
def test_regular_fields(self):
|
def test_regular_fields(self):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user