Add help texts to ModelSerializer property fields

If a field of a model wich is a read-only property is included in a
ModelSerializer, automátically set its help text to the docstring of the
property function. I used this to work with the documentation tool
django-rest-swagger.
This commit is contained in:
Matías Lang 2015-11-02 13:46:39 -03:00
parent d6b9cf6b6b
commit 0135d7ca5e
2 changed files with 11 additions and 2 deletions

View File

@ -1160,7 +1160,11 @@ class ModelSerializer(Serializer):
Create a read only field for model methods and properties.
"""
field_class = ReadOnlyField
field_kwargs = {}
func = getattr(model_class, field_name)
if func.__doc__:
field_kwargs = {'help_text': func.__doc__}
else:
field_kwargs = {}
return field_class, field_kwargs

View File

@ -72,6 +72,10 @@ class RegularFieldsModel(models.Model):
def method(self):
return 'method'
def docstring_method(self):
"""test"""
return 'method'
COLOR_CHOICES = (('red', 'Red'), ('blue', 'Blue'), ('green', 'Green'))
DECIMAL_CHOICES = (('low', decimal.Decimal('0.1')), ('medium', decimal.Decimal('0.5')), ('high', decimal.Decimal('0.9')))
@ -204,12 +208,13 @@ class TestRegularFieldMappings(TestCase):
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = RegularFieldsModel
fields = ('auto_field', 'method')
fields = ('auto_field', 'method', 'docstring_method')
expected = dedent("""
TestSerializer():
auto_field = IntegerField(read_only=True)
method = ReadOnlyField()
docstring_method = ReadOnlyField(help_text='test')
""")
self.assertEqual(repr(TestSerializer()), expected)