Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@extend_schema_field does not work on serializer used with many=True #1353

Open
mraerino opened this issue Dec 13, 2024 · 1 comment
Open

Comments

@mraerino
Copy link

Describe the bug

I have a field serializer that has no fields (just defines to_internal_value), so any field that uses it will be missing from the schema. I'm trying to override this with @extend_schema_field but that's not working if the serializer is used with many=True.

To Reproduce

from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers

@extend_schema_field(OpenApiTypes.INT64)
class RangeSerializer(serializers.Serializer):
  def to_internal_value(self, data):
    return data # usually there is more happening here

class ModelSerializer(serializers.Serializer):
  ranges = RangeSerializer(many=True)

Expected behavior

I expect the generated schema for ModelSerializer to be roughly this:

Model:
  type: object
  properties:
    ranges:
      type: array
        items:
          type: integer

this could be related to #694

I looked at this a little bit with a debugger and was able to find that this is related to how the many=True causes drf to wrap the serializer in a ListSerializer which hides the override annotation. In _unwrap_list_serializer (source) the code is directly calling resolve_serializer directly instead of checking for overrides again.

@tfranzel
Copy link
Owner

tfranzel commented Dec 18, 2024

Hi,

unfortunately the extend_schema_field decorator is not meant to be used on serializer. As the name suggests it is meant to be used with serializer fields. extend_schema_serializer, which would be the right decorator, does not allow this kind of manipulation.

I get this is a simplified example but are you not using a IntegerField instead of RangeSerializer?

If you want this to work you need to write a serializer extension for this: https://drf-spectacular.readthedocs.io/en/latest/customization.html#declare-serializer-magic-with-openapiserializerextension

There are quite a few example usages in the codebase under contrib on how to use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants