Skip to content

Commit

Permalink
Test Serializer exclude for declared fields (#5599)
Browse files Browse the repository at this point in the history
* Test current behavior of exclude+declared field

* Assert declared fields are not present in exclude
  • Loading branch information
Ryan P Kilby authored and carltongibson committed Nov 20, 2017
1 parent ff556a9 commit a3df1c1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions rest_framework/serializers.py
Expand Up @@ -1102,6 +1102,17 @@ def get_field_names(self, declared_fields, info):
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 "
Expand Down
16 changes: 16 additions & 0 deletions tests/test_model_serializer.py
Expand Up @@ -900,6 +900,22 @@ class Meta:
"Cannot set both 'fields' and 'exclude' options on serializer ExampleSerializer."
)

def test_declared_fields_with_exclude_option(self):
class ExampleSerializer(serializers.ModelSerializer):
text = serializers.CharField()

class Meta:
model = MetaClassTestModel
exclude = ('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):
def test_queryset_all(self):
Expand Down

0 comments on commit a3df1c1

Please sign in to comment.