Test Serializer exclude for declared fields (#5599)

* Test current behavior of exclude+declared field

* Assert declared fields are not present in exclude
This commit is contained in:
Ryan P Kilby 2017-11-20 03:51:16 -05:00 committed by Carlton Gibson
parent ff556a91fd
commit a3df1c1199
2 changed files with 27 additions and 0 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

@ -900,6 +900,22 @@ class TestSerializerMetaClass(TestCase):
"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):