【问题标题】:how to solve the circulating in nested serializers in django rest API?如何解决 django rest API 中嵌套序列化程序中的循环?
【发布时间】:2022-11-21 21:47:55
【问题描述】:

我正在尝试编写嵌套序列化器,但它显示 KeyError:

我写了这样的序列化器enter image description here

我写了这样的模型enter image description here

【问题讨论】:

  • 请使用代码块而不是屏幕截图。

标签: python-3.x django-rest-framework


【解决方案1】:

如果序列化程序在同一文件中定义,则可以按原样使用,如果它们来自其他模块,则可以导入它们。
由于您的所有模型似乎都在同一个模块中,因此您可以将所有序列化程序放在同一个文件中。例如:

from another_module.serializers import TestSerializer

class JobSerializer(serializers.ModelSerializer):

    class Meta:
        model = Job
        fields = '__all__'


class ApplicantSerializer(serializers.ModelSerializer):
    job = JobSerializer(many=True)
    test = TestSerializer()  # Just here as an example

    class Meta:
        model = ApplicantProfile
        fields = '__all__'

【讨论】:

    猜你喜欢
    • 2014-08-20
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2015-03-25
    相关资源
    最近更新 更多