Drf-yasg: Support for SerializerMethodField?

Created on 2 Jun 2018  路  3Comments  路  Source: axnsan12/drf-yasg

It would be useful for drf-yasg to support SerializerMethodField - I've not tried this yet, but I wonder if using py3.5+ type hinting to get the return type of the serializer method would work?

feature proposal

Most helpful comment

So maybe it'd be more useful to have a decorator for use with the SerializerMethodField methods a bit like swagger_auto_schema works on actions?`

This could work and seems like a clean enough API.

@swagger_serializer_method(serializer_class=SomeOtherSerializer)

Something to consider is that the return value will not necessarily be a serializer-generated object (i.e. it could be a plain int, or a list, etc)

All 3 comments

Actually thinking about this, hinting the return type wouldn't help much, since that's not going to give you the serializer class.

My main use case for this is where I have a SerializerMethodField that uses a serializer class in its implementation. So maybe it'd be more useful to have a decorator for use with the SerializerMethodField methods a bit like swagger_auto_schema works on actions?

Something like:

from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers

class SomeOtherSerializer(serializers.Serializer):
   ...

class UserSerializer(serializers.ModelSerializer):
    other_stuff = serializers.SerializerMethodField()

    class Meta:
        model = User

    @swagger_serializer_method(serializer_class=SomeOtherSerializer)
    def get_other_stuff(self, obj):
        # ...calculate something...
        return SomeOtherSerializer(something).data

So maybe it'd be more useful to have a decorator for use with the SerializerMethodField methods a bit like swagger_auto_schema works on actions?`

This could work and seems like a clean enough API.

@swagger_serializer_method(serializer_class=SomeOtherSerializer)

Something to consider is that the return value will not necessarily be a serializer-generated object (i.e. it could be a plain int, or a list, etc)

Hmm, is there a work-around for the time being? We have a similar issue where we're returning an int, but YASG thinks it's a string.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

beaugunderson picture beaugunderson  路  5Comments

hnykda picture hnykda  路  3Comments

agethecoolguy picture agethecoolguy  路  4Comments

vinayan3 picture vinayan3  路  5Comments

csdenboer picture csdenboer  路  3Comments