mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-16 19:41:06 +03:00
Enforce field_name != source
This commit is contained in:
parent
127c0bd3d6
commit
fb1546ee50
|
@ -160,6 +160,17 @@ class Field(object):
|
||||||
"""
|
"""
|
||||||
Setup the context for the field instance.
|
Setup the context for the field instance.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# In order to enforce a consistent style, we error if a redundant
|
||||||
|
# 'source' argument has been used. For example:
|
||||||
|
# my_field = serializer.CharField(source='my_field')
|
||||||
|
assert self._kwargs.get('source') != field_name, (
|
||||||
|
"It is redundant to specify `source='%s'` on field '%s' in "
|
||||||
|
"serializer '%s', as it is the same the field name. "
|
||||||
|
"Remove the `source` keyword argument." %
|
||||||
|
(field_name, self.__class__.__name__, parent.__class__.__name__)
|
||||||
|
)
|
||||||
|
|
||||||
self.field_name = field_name
|
self.field_name = field_name
|
||||||
self.parent = parent
|
self.parent = parent
|
||||||
self.root = root
|
self.root = root
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from rest_framework import fields
|
from rest_framework import fields, serializers
|
||||||
import datetime
|
import datetime
|
||||||
import django
|
import django
|
||||||
import pytest
|
import pytest
|
||||||
|
@ -69,6 +69,17 @@ class TestFieldOptions:
|
||||||
output = field.run_validation()
|
output = field.run_validation()
|
||||||
assert output is 123
|
assert output is 123
|
||||||
|
|
||||||
|
def test_redundant_source(self):
|
||||||
|
class ExampleSerializer(serializers.Serializer):
|
||||||
|
example_field = serializers.CharField(source='example_field')
|
||||||
|
with pytest.raises(AssertionError) as exc_info:
|
||||||
|
ExampleSerializer()
|
||||||
|
assert str(exc_info.value) == (
|
||||||
|
"It is redundant to specify `source='example_field'` on field "
|
||||||
|
"'CharField' in serializer 'ExampleSerializer', as it is the "
|
||||||
|
"same the field name. Remove the `source` keyword argument."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Tests for field input and output values.
|
# Tests for field input and output values.
|
||||||
# ----------------------------------------
|
# ----------------------------------------
|
||||||
|
|
Loading…
Reference in New Issue
Block a user