drf-spectacular icon indicating copy to clipboard operation
drf-spectacular copied to clipboard

Read-only model fields cannot be nullable

Open avere001 opened this issue 3 years ago • 1 comments

This issue is the same that drf-yasg has: https://github.com/axnsan12/drf-yasg/issues/310

The fundamental issue as described in https://github.com/axnsan12/drf-yasg/issues/310#issuecomment-468879166 is DRF itself https://github.com/encode/django-rest-framework/blob/31bf59708121127994bdbcd038f4f76bb28059d7/rest_framework/utils/field_mapping.py#L271-L274

It would be useful if drf-spectacular could overcome this issue by inspecting the models itself to determine if the field is nullable. Since It is not feasible in my case to add the extra_kwargs as suggested by the linked comment I have written a hook to deal with specific fields.

My current workaround is something similar to this:

def nullable_fields(result, generator, request, public):
    for component in generator.registry._components.values():
        if 'properties' in component.schema:
            props = component.schema['properties']
            for prop_name in [...]:
                if prop_name in props:
                    props[prop_name]['nullable'] = True

    return result

avere001 avatar May 14 '21 00:05 avere001

as you and axnsan12 have stated, this is a DRF issue. just for the record, the extra_kwargs solution also works for drf-spectacular. glad you found a workaround with a hook.

i may be possible to rerun rest_framework.utils.field_mapping.get_field_kwargs() to extract more info, but i'll have to investigate that.

tfranzel avatar May 14 '21 10:05 tfranzel

thanks to @TheSuperiorStanislav, this got resolved upstream with encode/django-rest-framework#8536 :heart:

tfranzel avatar Nov 21 '22 19:11 tfranzel