【问题标题】:How can i serialize that dictionary in Django?如何在 Django 中序列化该字典?
【发布时间】:2020-02-06 18:29:43
【问题描述】:
{'test': <Test: BOFEGRI_CGC_M: 2c942c01f8bfds498581a5d47d75fc020b-Started>, 'answers': <QuerySet [<TestQuestionAnswer: 2c942c01f8b4498581a5d47d75fc020b: question nr. 3, answer nr. 1, correct True>, <TestQuestionAnswer: 2c942c01f8b4498581a5d47d75fc020b: question nr. 3, answer nr. 2, correct False>, <TestQuestionAnswer: 2c942c01f8b4498581a5d47d75fc020b: question nr. 3, answer nr. 3, correct False>, <TestQuestionAnswer: 2c942c01f8b4ds98581a5d47d75fc020b: question nr. 3, answer nr. 4, correct False>]>, 'test_question': <TestQuestion: 2c942c01f8b4498581a5d47d75fc020b: nr=3>, 'test_button_list': [[{'number': 1, 'answered': False, 'correct': False}, {'number': 2, 'answered': False, 'correct': False}, {'number': 3, 'answered': False, 'correct': False}, {'number': 4, 'answered': False, 'correct': False}, {'number': 5, 'answered': False, 'correct': False}]], 'view': <tests.views.DifficultTestView object at 0x7f44e7e9c550>, 'form': <TestForm bound=False, valid=Unknown, fields=(AnswerRadioButton1;AnswerRadioButton2;AnswerRadioButton3;AnswerRadioButton4)>}

在我看来:

context = self.get_context_data()
        print(self.get_context_data())
        html = render_to_string('difficult_test.html', context)

        if self.request.is_ajax():

            return http.JsonResponse({"html":html, "context":context})
        return response 

如果我尝试序列化,我会收到以下响应:TypeError: is not JSON serializable

【问题讨论】:

    标签: json django ajax serialization


    【解决方案1】:

    如果您想问如何序列化 python 对象,那么 'pickle' 内置库允许该功能。

    例子:

    import pickle
    
    mapping = {'earth': [432, 762, 3297]}
    
    result = pickle.dumps(mapping)
    print(result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 2023-03-28
      • 2011-05-13
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      相关资源
      最近更新 更多