"Django序列化器中to_representation中包含不在模型中的字段"

2024-09-30 06:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个Django序列化程序,我试图得到一个特定的输出,但失败了。下面是序列化程序:

class MedTestsGetSerializer(serializers.ModelSerializer):
    test_type = MedTestsTypeNameSerializer(source='medteststypetest_id')

    class Meta:
        model = MedTests
        fields = ('medtests_id',
                  'test_type',)

    def to_representation(self, value):
        return '%s: %s' % (value.medtests_id, value.test_type)

现在理论上,这应该会给我输出{"uuid-goes-here-right-now": "test type name"},但它没有(这甚至不是我想要的最终版本)

它抛出的错误是'MedTests' object has no attribute 'test_type'

现在我的最终目标是这样:

{"uuid-goes-here-right-now":{"test_type":"test name"}}

但我想不通。如何控制输出将dict作为值放入uuid键,内部dict以标签作为键,内部dict以值作为字段。基本上是这样的:

{VALUE OF MEDTESTS_ID: {"test_type": VALUE OF TEST_TYPE}}

仅供参考,MedTestsTypeNameSerializer只返回一个字符串


Tags: test程序rightid序列化hereuuidvalue

热门问题