New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to set a field type on SerializerMethodField for OpenAPI schema generation? #7140
Comments
Hi @Lucidiot. I guess the immediate way to do this would be to override You can either do that per-serializer/view to expect the field in question, or add an attribute like you say. We'll come round to something in this way eventually, but currently I'm not sure about the best option, in terms of API. |
For me, I think the API I'd prefer is something using type hinting like: def get_foo(self, obj) -> int:
return 1 It works in every Python version currently supported. This idea was used in #7089 but it wasn't separated out into another PR. Looking at that implementation, it seems like it doesn't handle collections. At some point you'd be better using a nested serializer, but I think simple cases like @carlfarrington what do you think? Is it worth trying this approach or are there problems with it? If it's worth trying, is it also worth getting something basic in that can handle basic types and ignore nested fields for now or would we want (nested or not) arrays and objects from the start? |
We'll promote and document |
Consider this useless serializer:
Assuming you added this serializer in an endpoint and generated the OpenAPI schema, the serializer would look like this:
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, likeserializers.SerializerMethodField(output_field=serializers.IntegerField())
, similarly to Django's Query ExpressionsA decorator, like
openapi_type(serializers.SerializerMethodField(), serializers.IntegerField())
An attribute, similarly to setting descriptions on admin actions:
Simply something DRF does not support, which probably should be documented somewhere as a possible caveat.
The text was updated successfully, but these errors were encountered: