mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-04 20:40:14 +03:00
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:
parent
d6b9cf6b6b
commit
0135d7ca5e
|
@ -1160,7 +1160,11 @@ class ModelSerializer(Serializer):
|
||||||
Create a read only field for model methods and properties.
|
Create a read only field for model methods and properties.
|
||||||
"""
|
"""
|
||||||
field_class = ReadOnlyField
|
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
|
return field_class, field_kwargs
|
||||||
|
|
||||||
|
|
|
@ -72,6 +72,10 @@ class RegularFieldsModel(models.Model):
|
||||||
def method(self):
|
def method(self):
|
||||||
return 'method'
|
return 'method'
|
||||||
|
|
||||||
|
def docstring_method(self):
|
||||||
|
"""test"""
|
||||||
|
return 'method'
|
||||||
|
|
||||||
|
|
||||||
COLOR_CHOICES = (('red', 'Red'), ('blue', 'Blue'), ('green', 'Green'))
|
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')))
|
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 TestSerializer(serializers.ModelSerializer):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = RegularFieldsModel
|
model = RegularFieldsModel
|
||||||
fields = ('auto_field', 'method')
|
fields = ('auto_field', 'method', 'docstring_method')
|
||||||
|
|
||||||
expected = dedent("""
|
expected = dedent("""
|
||||||
TestSerializer():
|
TestSerializer():
|
||||||
auto_field = IntegerField(read_only=True)
|
auto_field = IntegerField(read_only=True)
|
||||||
method = ReadOnlyField()
|
method = ReadOnlyField()
|
||||||
|
docstring_method = ReadOnlyField(help_text='test')
|
||||||
""")
|
""")
|
||||||
self.assertEqual(repr(TestSerializer()), expected)
|
self.assertEqual(repr(TestSerializer()), expected)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user