django - 在 Django Rest 框架中序列化不是模型的字典

标签 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'}}

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

class PsudoTests:

    def __init__(self,body):
        self.body = body

也是一个序列化器:

class PsudoTestSerializer(serializers.Serializer):
    body = serializers.DictField()

现在在 api View 中:

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

现在,当我访问该网址时,出现一个关键错误:

"Got KeyError when attempting to get a value for field body on serializer PsudoTestSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'body'."

当我访问 api url 时,如何成功获取 json 格式的字典。 谢谢。

最佳答案

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

关于django - 在 Django Rest 框架中序列化不是模型的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49717118/

相关文章:

python - Django REST 框架 CSRF 失败 : CSRF cookie not set

django-rest-framework - 使用djangorest框架,如何为现有父对象添加新的嵌套子对象

python - 如何在区 block 链上存储交易日志?

python - Django 模板继承不提供 css?

python - 如何序列化和反序列化 Django ORM 查询(不是查询集)?

python - Django 使用 PyCharm 时出错 : "' function' object has no attribute 'using' "

python - 在 DRF 中同时支持 JSON 和文件分段上传的测试

python - 与南方陷入移民冲突

Django 1.10 对子目录中的应用程序的迁移支持

Django休息框架: Best practices?