【问题标题】:Django Rest Framework: Why does PrimaryKeyRelatedField document as a string in the schema when read_only?Django Rest Framework:为什么PrimaryKeyRelatedField在read_only时在模式中以字符串形式记录?
【发布时间】:2020-07-24 16:54:27
【问题描述】:

我有一个带有 PrimaryKeyRelatedField 的序列化程序:

field_name = serializers.PrimaryKeyRelatedField(queryset=ModelClass.objects.all(), read_only=False)

通过此设置,Schema 将参数正确地识别为整数(PK)。但是,当我更改为:

field_name = serializers.PrimaryKeyRelatedField(read_only=True)

(它不会让你同时指定querysetread_only)然后参数在Schema中被识别为字符串。

为什么会这样?这是正确/预期的行为还是错误?

【问题讨论】:

    标签: python-3.x django django-rest-framework swagger-ui openapi


    【解决方案1】:

    好吧,我已经在这个问题上猛烈抨击了足够长的时间来发布 SO,但随着我继续深入研究它,我认为我正在取得一些进展。

    rest_framework/schemas/openapi.py:380 内部的map_field() 中,您会发现以下内容:

    if isinstance(field, serializers.PrimaryKeyRelatedField):
        model = getattr(field.queryset, 'model', None)
        if model is not None:
            model_field = model._meta.pk
            if isinstance(model_field, models.AutoField):
                return {'type': 'integer'}
    

    RelatedField 不允许您在 read_only=True 时指定查询集,因此当 read_only=True 时,上述代码 sn-p 中的“模型”始终为 None,您最终会在map_field 函数的底部。

    所以这解释了为什么它目前正在发生,并且似乎是 DRF 中的一个错误,但现在我想我只需要研究适当的修复方法。

    我已经针对 DRF 提出了相应的问题:https://github.com/encode/django-rest-framework/issues/7427

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 2015-09-30
      • 1970-01-01
      • 2020-01-15
      • 2018-05-19
      • 2018-08-18
      相关资源
      最近更新 更多