Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise error when ModelSerializer used with abstract model #2757

Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
@@ -823,6 +823,10 @@ def get_fields(self):
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)
model = getattr(self.Meta, 'model')
7 changes: 7 additions & 0 deletions rest_framework/utils/model_meta.py
Original file line number Diff line number Diff line change
@@ -167,3 +167,10 @@ def _merge_relationships(forward_relations, reverse_relations):
list(forward_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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be checking hasattr(model, '_meta') (not 'Meta').

24 changes: 24 additions & 0 deletions tests/test_model_serializer.py
Original file line number Diff line number Diff line change
@@ -94,6 +94,30 @@ class Meta:
msginitial = 'Got a `TypeError` when calling `OneFieldModel.objects.create()`.'
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):
def test_regular_fields(self):