Skip to content

How to set a field type on SerializerMethodField for OpenAPI schema generation? #7140

@Lucidiot

Description

@Lucidiot

Consider this useless serializer:

class MySerializer(serializers.Serializer):

    random_number = serializers.SerializerMethodField()

    def get_random_number(self):
        # Chosen by fair dice roll.
        # Guaranteed to be random.
        return 4

Assuming you added this serializer in an endpoint and generated the OpenAPI schema, the serializer would look like this:

properties:
  random_number:
    type: string
  required:
  - random_number

The issue here is there is no way to tell DRF to use type: number here. I thought of a few possibilities:

  • An output_field attribute, like serializers.SerializerMethodField(output_field=serializers.IntegerField()), similarly to Django's Query Expressions

  • A decorator, like openapi_type(serializers.SerializerMethodField(), serializers.IntegerField())

  • An attribute, similarly to setting descriptions on admin actions:

    random_number = serializers.SerializerMethodField()
    
    def get_random_number(self):
        return 4
    
    get_random_number.output_field = serializers.IntegerField()
  • Simply something DRF does not support, which probably should be documented somewhere as a possible caveat.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    pFad - Phonifier reborn

    Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

    Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


    Alternative Proxies:

    Alternative Proxy

    pFad Proxy

    pFad v3 Proxy

    pFad v4 Proxy