Assert declared fields are not present in exclude

This commit is contained in:
Ryan P Kilby 2017-11-15 16:28:49 -05:00
parent 0b72285f0e
commit 4e7e728ab9
2 changed files with 18 additions and 1 deletions

View File

@ -1102,6 +1102,17 @@ class ModelSerializer(Serializer):
if exclude is not None:
# If `Meta.exclude` is included, then remove those fields.
for field_name in exclude:
assert field_name not in self._declared_fields, (
"Cannot both declare the field '{field_name}' and include "
"it in the {serializer_class} 'exclude' option. Remove the "
"field or, if inherited from a parent serializer, disable "
"with `{field_name} = None`."
.format(
field_name=field_name,
serializer_class=self.__class__.__name__
)
)
assert field_name in fields, (
"The field '{field_name}' was included on serializer "
"{serializer_class} in the 'exclude' option, but does "

View File

@ -908,7 +908,13 @@ class TestSerializerMetaClass(TestCase):
model = MetaClassTestModel
exclude = ('text',)
assert list(ExampleSerializer().fields) == ['id', 'text']
expected = (
"Cannot both declare the field 'text' and include it in the "
"ExampleSerializer 'exclude' option. Remove the field or, if "
"inherited from a parent serializer, disable with `text = None`."
)
with self.assertRaisesMessage(AssertionError, expected):
ExampleSerializer().fields
class Issue2704TestCase(TestCase):