7
votes

I am using django, django drf and drf-yasg to generate write my BE and generate documentation.

I have a model called User and a serializer for a user:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = users_models.User
        fields = (users_models.User.first_name.field_name,
                  users_models.User.last_name.field_name,)

and I have some method Foo which gets two users. This is what a serializer for the request looks like:

class FooRequestSerializer(serializers.ModelSerializer):
      first_user = UserSerializer(help_text="first user")
      second_user = UserSerializer(help_text="second user")

when I generate a swagger json scheme for this I view the json and the redoc I see that:

  1. first_user and second_user have the same ref name ($ref)
  2. The description of the second_user and the redoc reads "first user" and not second user. this is because the description is taken from the $ref which has the first user description.

I noted that if I make sure the ref names are distinct then the the redoc reads fine since first_user and second_user get their own description. The problem comes since I also want to be able to later use swagger codegen to create Java stubs, so the solution and from what I understand there is a different class for each distinct ref name. Ideally I would see that the call to foo is something like

Foo(User first_user, User second_user)

This gets me to the problem that:

  • If first_user and second_user has the same ref name then the redoc reads wrong and the second user has the first user description.
  • If first_user and second_user has distinct ref names then the redoc works but I get two disticnt classes generated, say

    Foo(FirstUser first_user, SecondUser second_user)

What do I need to to inorder to have both working redoc and generated classes as expected ?

1

1 Answers

8
votes

According to drf-yasg docs here, you can specify a ref_name in a Meta class of serializer. Therefore, something like this should work (although not very clean solution):

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = users_models.User
        fields = (users_models.User.first_name.field_name,
                  users_models.User.last_name.field_name,)


class FirstUserSerializer(UserSerializer):
    class Meta:
        ref_name = "User 1"


class SecondUserSerializer(UserSerializer):
    class Meta:
        ref_name = "User 2"


class FooRequestSerializer(serializers.ModelSerializer):
      first_user = FirstUserSerializer(help_text="first user")
      second_user = SecondUserSerializer(help_text="second user")