ast
ast

Reputation: 1

unable to specify the fields in drf queryset using drf-yasg

class ABC(generics.ListCreateApiView):
         @swagger_auto_schema(
             operation_description="THIS API IS TO CREATE MESSAGES IN A LIST ",
             auto_schema=AcceptFormDataSchema,
             request_body=MessageGetSerializer
         )
         def get_queryset(self):
             data =self.request.GET.get("code")
             ...
         @swagger_auto_schema(
             operation_description="THIS API IS TO CREATE MESSAGES IN A LIST ",
             request_body=openapi.Schema(
                 type=openapi.TYPE_OBJECT,
                 required=["data"],
                 properties={
                    "code": openapi.Schema(type=openapi.TYPE_STRING),
                 },
             )
         )
         def post(self, request):
             brand_code = request.data.get("code")
             ...
#serializer.py

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Messages
        fields = ("message_id", "content", "description")

My post method is working fine with the fields which I required using the same serializer but it's not working for the get_queryset method. Can anyone please suggest something on how I will get the fields using drf-yasg?

Upvotes: 0

Views: 1065

Answers (1)

EDG956
EDG956

Reputation: 982

You shouldn't decorate get_queryset as that is an internal function and not part of the ApiView's endpoints. You probably see a get request in swagger because the ListCreateApiView you're using defines handlers for get and post methods.

Since you're not overriding the get method handler, you can inject a decorator into the ApiView's get method using Django's method_decorator, as indicated in drf-yasg section on swagger_auto_schema decorator.

The following is an example implementation to your ApiView that should also document the get endpoint.

@method_decorator(
    name='get',
    decorator=swagger_auto_schema(
        operation_description="description from swagger_auto_schema via method_decorator"
    )
)
class ABC(generics.ListCreateApiView):
    serializer_class = MessageSerializer

    def get_queryset(self):
        data =self.request.GET.get("code")
        ...
    @swagger_auto_schema(
        operation_description="THIS API IS TO CREATE MESSAGES IN A LIST ",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=["data"],
            properties={
                "code": openapi.Schema(type=openapi.TYPE_STRING),
            },
         )
     )
     def post(self, request):
         brand_code = request.data.get("code")
         ...

--------------
#serializer.py

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Messages
        fields = ("message_id", "content", "description")

Upvotes: 0

Related Questions