Skip to content

Commit 4e7e728

Browse files
author
Ryan P Kilby
committed
Assert declared fields are not present in exclude
1 parent 0b72285 commit 4e7e728

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

rest_framework/serializers.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1102,6 +1102,17 @@ def get_field_names(self, declared_fields, info):
11021102
if exclude is not None:
11031103
# If `Meta.exclude` is included, then remove those fields.
11041104
for field_name in exclude:
1105+
assert field_name not in self._declared_fields, (
1106+
"Cannot both declare the field '{field_name}' and include "
1107+
"it in the {serializer_class} 'exclude' option. Remove the "
1108+
"field or, if inherited from a parent serializer, disable "
1109+
"with `{field_name} = None`."
1110+
.format(
1111+
field_name=field_name,
1112+
serializer_class=self.__class__.__name__
1113+
)
1114+
)
1115+
11051116
assert field_name in fields, (
11061117
"The field '{field_name}' was included on serializer "
11071118
"{serializer_class} in the 'exclude' option, but does "

tests/test_model_serializer.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -908,7 +908,13 @@ class Meta:
908908
model = MetaClassTestModel
909909
exclude = ('text',)
910910

911-
assert list(ExampleSerializer().fields) == ['id', 'text']
911+
expected = (
912+
"Cannot both declare the field 'text' and include it in the "
913+
"ExampleSerializer 'exclude' option. Remove the field or, if "
914+
"inherited from a parent serializer, disable with `text = None`."
915+
)
916+
with self.assertRaisesMessage(AssertionError, expected):
917+
ExampleSerializer().fields
912918

913919

914920
class Issue2704TestCase(TestCase):

0 commit comments

Comments
 (0)