Skip to content

Commit

Permalink
Merge pull request encode#5388 from founders4schools/fix/named-source
Browse files Browse the repository at this point in the history
Fix ModelSerializer custom named fields with source on model
  • Loading branch information
Carlton Gibson authored Sep 4, 2017
2 parents 79be20a + 66b2c61 commit 71ad99e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
4 changes: 3 additions & 1 deletion rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1010,7 +1010,9 @@ def get_fields(self):
continue

extra_field_kwargs = extra_kwargs.get(field_name, {})
source = extra_field_kwargs.get('source', '*') != '*' or field_name
source = extra_field_kwargs.get('source', '*')
if source == '*':
source = field_name

# Determine the serializer field class and keyword arguments.
field_class, field_kwargs = self.build_field(
Expand Down
21 changes: 21 additions & 0 deletions tests/test_model_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1135,3 +1135,24 @@ class Meta:
serializer = TestUniqueChoiceSerializer(data={'name': 'choice1'})
assert not serializer.is_valid()
assert serializer.errors == {'name': ['unique choice model with this name already exists.']}


class TestFieldSource(TestCase):
def test_named_field_source(self):
class TestSerializer(serializers.ModelSerializer):

class Meta:
model = RegularFieldsModel
fields = ('number_field',)
extra_kwargs = {
'number_field': {
'source': 'integer_field'
}
}

expected = dedent("""
TestSerializer():
number_field = IntegerField(source='integer_field')
""")
self.maxDiff = None
self.assertEqual(unicode_repr(TestSerializer()), expected)

0 comments on commit 71ad99e

Please sign in to comment.