我读过一些关于序列化字典的答案和帖子。但我仍然无法让它发挥作用。 问题就在这里。 我在 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 serializerPsudoTestSerializer
.\nThe serializer field might be named incorrectly and not match any attribute or key on thedict
instance.\nOriginal exception text was: 'body'."
当我访问 api url 时,如何成功获取 json 格式的字典。 谢谢。
最佳答案
这里不需要序列化器。只需将其直接转储为 JSON。
关于django - 在 Django Rest 框架中序列化不是模型的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49717118/