Merge pull request #5388 from founders4schools/fix/named-source

Fix ModelSerializer custom named fields with source on model
This commit is contained in:
Carlton Gibson 2017-09-04 17:24:36 +02:00 committed by GitHub
commit 71ad99e0b2
2 changed files with 24 additions and 1 deletions

View File

@ -1010,7 +1010,9 @@ class ModelSerializer(Serializer):
continue continue
extra_field_kwargs = extra_kwargs.get(field_name, {}) 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. # Determine the serializer field class and keyword arguments.
field_class, field_kwargs = self.build_field( field_class, field_kwargs = self.build_field(

View File

@ -1135,3 +1135,24 @@ class Test5004UniqueChoiceField(TestCase):
serializer = TestUniqueChoiceSerializer(data={'name': 'choice1'}) serializer = TestUniqueChoiceSerializer(data={'name': 'choice1'})
assert not serializer.is_valid() assert not serializer.is_valid()
assert serializer.errors == {'name': ['unique choice model with this name already exists.']} 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)