Skip to content

Commit 3578ba6

Browse files
author
Ryan P Kilby
committed
Assert declared fields are not present in exclude
1 parent 33d3bd9 commit 3578ba6

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

rest_framework/serializers.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1099,12 +1099,20 @@ def get_field_names(self, declared_fields, info):
10991099
# Use the default set of field names if `Meta.fields` is not specified.
11001100
fields = self.get_default_field_names(declared_fields, info)
11011101

1102-
# deduplicate field names (occurs when a declared fields matches a model field)
1103-
fields = list(OrderedDict.fromkeys(fields))
1104-
11051102
if exclude is not None:
11061103
# If `Meta.exclude` is included, then remove those fields.
11071104
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+
11081116
assert field_name in fields, (
11091117
"The field '{field_name}' was included on serializer "
11101118
"{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']
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)