# Buggy code
def _map_model_field(self, model_field, direction):
    assert isinstance(model_field, models.Field)
    # to get a fully initialized serializer field we use DRF's own init logic
    try:
        field_cls, field_kwargs = serializers.ModelSerializer().build_field(
            field_name=model_field.name,
            info=get_field_info(model_field.model),
            model_class=model_field.model,
            nested_depth=0,
        )
        field = field_cls(**field_kwargs)
    except:  # noqa
        field = None

    # For some cases, the DRF init logic either breaks (custom field with internal type) or
    # the resulting field is underspecified with regards to the schema (ReadOnlyField).
    if field and not anyisinstance(
        field, [serializers.ReadOnlyField, serializers.ModelField]
    ):
        return self._map_serializer_field(field, direction)
    elif isinstance(model_field, models.ForeignKey):
        return self._map_model_field(model_field.target_field, direction)
    elif hasattr(models, "JSONField") and isinstance(model_field, models.JSONField):
        # fix for DRF==3.11 with django>=3.1 as it is not yet represented in the field_mapping
        return build_basic_type(OpenApiTypes.OBJECT)
    elif hasattr(models, model_field.get_internal_type()):
        # be graceful when the model field is not explicitly mapped to a serializer
        internal_type = getattr(models, model_field.get_internal_type())
        field_cls = serializers.ModelSerializer.serializer_field_mapping.get(
            internal_type
        )
        if not field_cls:
            warn(
                f'model field "{model_field.get_internal_type()}" has no mapping in '
                f'ModelSerializer. it may be a deprecated field. defaulting to "string"'
            )
            return build_basic_type(OpenApiTypes.STR)
        return self._map_serializer_field(field_cls(), direction)
    else:
        error(
            f'could not resolve model field "{model_field}". failed to resolve through '
            f"serializer_field_mapping, get_internal_type(), or any override mechanism. "
            f'defaulting to "string"'
        )
        return build_basic_type(OpenApiTypes.STR)


# Traceback (AttributeError)
Internal Server Error: /api/schema/
Traceback (most recent call last):
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.9/contextlib.py", line 79, in inner
return func(*args, **kwds)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/views.py", line 61, in get
return self._get_schema_response(request)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/views.py", line 65, in _get_schema_response
return Response(generator.get_schema(request=request, public=self.serve_public))
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/generators.py", line 188, in get_schema
paths=self.parse(request, public),
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/generators.py", line 165, in parse
operation = view.schema.get_operation(path, path_regex, method, self.registry)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 62, in get_operation
parameters = self._get_parameters()
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 185, in _get_parameters
**dict_helper(self._resolve_path_parameters(path_variables)),
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 324, in _resolve_path_parameters
schema = self._map_model_field(model_field, direction=None)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 389, in _map_model_field
return self._map_serializer_field(field, direction)
File "/home/alex/.cache/pypoetry/virtualenvs/foobarbaz-6qdzD22P-py3.9/lib/python3.9/site-packages/drf_spectacular/openapi.py", line 461, in _map_serializer_field
model_field = field.parent.Meta.model._meta.pk
AttributeError: 'NoneType' object has no attribute 'Meta'

# Fixed code
def _map_model_field(self, model_field, direction):
    assert isinstance(model_field, models.Field)
    # to get a fully initialized serializer field we use DRF's own init logic
    try:
        field_cls, field_kwargs = serializers.ModelSerializer().build_field(
            field_name=model_field.name,
            info=get_field_info(model_field.model),
            model_class=model_field.model,
            nested_depth=0,
        )
        field = field_cls(**field_kwargs)
    except:  # noqa
        field = None

    # For some cases, the DRF init logic either breaks (custom field with internal type) or
    # the resulting field is underspecified with regards to the schema (ReadOnlyField).
    if field and isinstance(field, serializers.PrimaryKeyRelatedField):
        # special case handling only for _resolve_path_parameters() where neither queryset nor
        # parent is set by build_field. patch in queryset as _map_serializer_field requires it
        if not field.queryset:
            field.queryset = model_field.related_model.objects.none()
        return self._map_serializer_field(field, direction)
    elif field and not anyisinstance(
        field, [serializers.ReadOnlyField, serializers.ModelField]
    ):
        return self._map_serializer_field(field, direction)
    elif isinstance(model_field, models.ForeignKey):
        return self._map_model_field(model_field.target_field, direction)
    elif hasattr(models, "JSONField") and isinstance(model_field, models.JSONField):
        # fix for DRF==3.11 with django>=3.1 as it is not yet represented in the field_mapping
        return build_basic_type(OpenApiTypes.OBJECT)
    elif hasattr(models, model_field.get_internal_type()):
        # be graceful when the model field is not explicitly mapped to a serializer
        internal_type = getattr(models, model_field.get_internal_type())
        field_cls = serializers.ModelSerializer.serializer_field_mapping.get(
            internal_type
        )
        if not field_cls:
            warn(
                f'model field "{model_field.get_internal_type()}" has no mapping in '
                f'ModelSerializer. it may be a deprecated field. defaulting to "string"'
            )
            return build_basic_type(OpenApiTypes.STR)
        return self._map_serializer_field(field_cls(), direction)
    else:
        error(
            f'could not resolve model field "{model_field}". failed to resolve through '
            f"serializer_field_mapping, get_internal_type(), or any override mechanism. "
            f'defaulting to "string"'
        )
        return build_basic_type(OpenApiTypes.STR)