在 Django restframework 中序列化不是模型的字典

Pra*_*dey 3 django django-rest-framework

我已经阅读了一些关于序列化字典的答案和帖子。但我仍然无法让它工作。这是问题所在。我在 django app 中做了一些数据处理,它返回这个字典(它有关于测验的信息):

{101: {'subject': 'General-Intelligence', 'topics': ['Coding Decoding', 'Dice & Boxes', 'Statement & Conclusion', 'Venn Diagram', 'Mirror and Water Image', 'Paper Cutting and Folding', 'Clock/Time', 'Matrix', 'Direction', 'Blood Relation', 'Series Test', 'Ranking', 'Mathematical Operations', 'Alphabet Test', 'Odd one out', 'Analogy'], 'num_questions': 25, 'creator': 'Rajesh K Swami'}}
Run Code Online (Sandbox Code Playgroud)

我想序列化这本字典。所以我所做的就是为这本词典创建了一个类。IE。

class PsudoTests:

    def __init__(self,body):
        self.body = body
Run Code Online (Sandbox Code Playgroud)

也是一个序列化器:

class PsudoTestSerializer(serializers.Serializer):
    body = serializers.DictField()
Run Code Online (Sandbox Code Playgroud)

现在在 api 视图中:

class TestListView(generics.ListAPIView):

    def get_serializer_class(self):
        serializer = PsudoTestSerializer

    def get_queryset(self):
        me = Studs(self.request.user)
        tests = me.toTake_Tests(1) # this method brings in the above dictionary that i want to serialize
        p_test = PsudoTests(tests) #this creates an instance of class created above

        return p_test
Run Code Online (Sandbox Code Playgroud)

现在,当我转到 url 时,出现一个关键错误:

"尝试获取body序列PsudoTestSerializer化程序字段的值时出现dictKeyError 。\n序列化程序字段可能命名不正确,并且与实例上的任何属性或键都不匹配。\n原始异常文本为:'body'。"

当我转到 api url 时,如何以 json 格式成功获取该字典。谢谢。

Dan*_*man 5

这里不需要序列化器。只需将其直接转储到 JSON。

  • 序列化程序不会帮助验证 JSON 的数据类型吗? (3认同)