Search code examples
django-rest-frameworkswaggeropenapidjango-serializerdrf-spectacular

Using extend_schema_field for custom field


I created a custom field named PictureField which creates thumbnails with uploaded images and I used it in my User model

User model:

class User(AbstractBaseUser):
    profile_image = PictureField(make_thumbnail=True)

My PictureField, gets an image file like django's ImageField and returns a dictionary like this:

{
    "image": {
      "url": "string",
      "name": "string"
    },
    "thumbnail": {
      "url": "string",
      "name": "string"
    } | None
}

Everything is fine and my custom field works correct. my problem is the schema that created with drf_spectacular. I don't know how to set this output to my PictureSerializerField. already, I set @extend_schema_field decorator for my field to BINARY (for being able to upload file with Swagger) and with this, my Response output is set to "string":

@extend_schema_field(OpenApiTypes.BINARY)
class PictureSerializerField(ImageField):
     ...

Now, my Swagger docs look like this:
I'm looking for something like below to show my output to Response and also I be able to upload file in Request:

@extend_schema_field({
    'request':OpenApiTypes.BINARY,
    'response': {}# My output example that I said above
})

my idea is creating an empty serializer class and set @extend_schema_serializer on that but I think it isn't good way and doesn't works.


Solution

  • Ok I've fixed it. just read a little OpenAPI documentation and also I saw @extend_schema_field supports dict parameter, so I write my code like this:

    @extend_schema_field({'type':"string",'format':'binary',
        'example':{
                 "image":{"url":"string","name":"string"},
                 "thumbnail":{"url":"string","name":"string"}
        }
    })
    class PictureSerializerField(ImageField):
        ...
    

    And it looks OK.enter image description here