Skip to content

Commit

Permalink
Allow redundant SerializerMethodField method names (encode#6767)
Browse files Browse the repository at this point in the history
  • Loading branch information
rpkilby authored and sigvef committed Dec 3, 2022
1 parent bf9b5b7 commit 1e29ac3
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 14 deletions.
6 changes: 0 additions & 6 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1835,12 +1835,6 @@ def bind(self, field_name, parent):
# 'method_name' argument has been used. For example:
# my_field = serializer.SerializerMethodField(method_name='get_my_field')
default_method_name = 'get_{field_name}'.format(field_name=field_name)
assert self.method_name != default_method_name, (
"It is redundant to specify `%s` on SerializerMethodField '%s' in "
"serializer '%s', because it is the same as the default method name. "
"Remove the `method_name` argument." %
(self.method_name, field_name, parent.__class__.__name__)
)

# The method name should default to `get_{field_name}`.
if self.method_name is None:
Expand Down
12 changes: 4 additions & 8 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -2212,17 +2212,13 @@ def get_example_field(self, obj):
}

def test_redundant_method_name(self):
# Prior to v3.10, redundant method names were not allowed.
# This restriction has since been removed.
class ExampleSerializer(serializers.Serializer):
example_field = serializers.SerializerMethodField('get_example_field')

with pytest.raises(AssertionError) as exc_info:
ExampleSerializer().fields
assert str(exc_info.value) == (
"It is redundant to specify `get_example_field` on "
"SerializerMethodField 'example_field' in serializer "
"'ExampleSerializer', because it is the same as the default "
"method name. Remove the `method_name` argument."
)
field = ExampleSerializer().fields['example_field']
assert field.method_name == 'get_example_field'


class TestValidationErrorCode:
Expand Down

0 comments on commit 1e29ac3

Please sign in to comment.