Skip to content

Commit

Permalink
add choice field display method handling #1228
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed May 7, 2024
1 parent a79bc5d commit e5b7361
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
9 changes: 8 additions & 1 deletion drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -893,7 +893,14 @@ def _map_serializer_field(self, field, direction, bypass_extensions=False):
return append_meta(build_basic_type(OpenApiTypes.STR), meta)

target = follow_field_source(model, source)
if callable(target):
if (
hasattr(target, "_partialmethod")
and target._partialmethod.func.__name__ == '_get_FIELD_display'
):
# the only way to detect an uninitialized partial method
# this is a convenience method for model choice fields and is mostly a string
schema = build_basic_type(str)
elif callable(target):
schema = self._map_response_type_hint(target)
elif isinstance(target, models.Field):
schema = self._map_model_field(target, direction)
Expand Down
25 changes: 25 additions & 0 deletions tests/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3385,3 +3385,28 @@ def view_func(request, format=None):
'baz': {'type': 'integer'},
'qux': {'items': {'type': 'integer'}, 'type': 'array'}
}


def test_model_choice_display_method_on_readonly(no_warnings):
class M15(models.Model):
SHIRT_SIZES = {"S": "Small", "M": "Medium", "L": "Large"}

name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)

class XSerializer(serializers.ModelSerializer):
field_name = serializers.ReadOnlyField(source='name')
field_shirts = serializers.ReadOnlyField(source='get_shirt_size_display')

class Meta:
model = M15
fields = '__all__'

class XViewset(viewsets.ModelViewSet):
queryset = M15.objects.all()
serializer_class = XSerializer

schema = generate_schema('x', XViewset)
assert schema['components']['schemas']['X']["properties"]["field_shirts"] == {
"readOnly": True, 'type': 'string'
}

0 comments on commit e5b7361

Please sign in to comment.