Skip to content

Commit a3df1c1

Browse files
Ryan P Kilbycarltongibson
authored andcommitted
Test Serializer exclude for declared fields (#5599)
* Test current behavior of exclude+declared field * Assert declared fields are not present in exclude
1 parent ff556a9 commit a3df1c1

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
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: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -900,6 +900,22 @@ class Meta:
900900
"Cannot set both 'fields' and 'exclude' options on serializer ExampleSerializer."
901901
)
902902

903+
def test_declared_fields_with_exclude_option(self):
904+
class ExampleSerializer(serializers.ModelSerializer):
905+
text = serializers.CharField()
906+
907+
class Meta:
908+
model = MetaClassTestModel
909+
exclude = ('text',)
910+
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
918+
903919

904920
class Issue2704TestCase(TestCase):
905921
def test_queryset_all(self):

0 commit comments

Comments
 (0)