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

Can swagger show different return values with extend_schema_field aligned with SerializerMethodField? #783

Closed
Sahayana opened this issue Aug 9, 2022 · 2 comments

Comments

@Sahayana
Copy link

Sahayana commented Aug 9, 2022

Hello,

with my poor ability to find references on google, I finally ended up choosing this area for asking problems.

Assuming that I set a custom field using SerializerMethodfield that returns 2 different values by a certain condition as below.

class MySerializer(serializer.ModelSerializer):
    
    product = serializers.SerializerMethodField()

    @extend_schema_field(field=OpenApiTypes.STR)
    def get_product(self, obj):
        if obj.product:
            return obj.product.name
        return {}

It should return string or empty dict by a condition but All I can set for this was string type with only one value.
Is it technically wrong for the swagger to show different values or I can do more customizing with this?

@Sahayana
Copy link
Author

I found a trick suggested in an issue #778.

As the document says here that overriding OpenApiSerializerFieldExtension is functionally same with adding field attribute in @extend_schema_field

When a customized serializer field given, It comes as Class so I can assign it with target_class,
but SerializerMethodField is defined as a function that normally starts with def get_.

then not sure how I can override OpenApiSerializerFieldExtension for this :(

@tfranzel
Copy link
Owner

As the document says here that overriding OpenApiSerializerFieldExtension is functionally same with adding field attribute in @extend_schema_field

yes. it does the same, but depending on what you need you have slightly different options.

You don't need OpenApiSerializerFieldExtension here. It is meant for custom fields. SerializerMethodField is not a custom field in that sense.

Use this, which is also doing the same as @extend_schema_field, but you have access to Union with that. It would also be possible to do this with @extend_schema_field but you would have to write a small raw schema.

   def get_product(self, obj) -> typing.Union[str, dict]:
      ...

an empty dict is a bit harder to model. This is a free-form dict.

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