【发布时间】:2020-02-26 13:15:12
【问题描述】:
我以非常特定的顺序从一些 django 模型中收集数据并将它们输出为 json 以在 React 中使用。
quiz = LessonQuiz.objects.filter(lesson=details).order_by('position')
quizdata = []
if quiz.count() > 0:
for a in quiz:
qz = LessonQuiz.objects.get(id=a.id)
item = {'id': qz.id, 'title': qz.title}
if qz.linkbutton_set.count() > 0:
buttons = qz.linkbutton_set.all()
for b in buttons:
item[b.id] = {
"id": b.id,
"type": b.qtype,
"text": b.text,
"link": b.link,
"color": b.color
}
quizdata.append(item)
此刻它返回我想要的所有数据如下,
[
{
"id": 3,
"title": "Do you agree?",
"1": {
"id": 1,
"type": "btn",
"text": "I agree",
"link": "/lesson/welcome/completed",
"color": "#e2574c"
},
"2": {
"id": 2,
"type": "btn",
"text": "I'm not sure I agree",
"link": "/contact",
"color": "#e2574c"
},
"3": {
"id": 3,
"type": "btn",
"text": "I have a suggestion",
"link": "/contact",
"color": "#e2574c"
}
}
]
但是,理想情况下,我希望在它自己的数组中包含数组 1、2 和 3,例如数据。
[
{
'id': 3,
'title': 'Do you agree?',
'data': [
1: {
'id': 1,
'type': 'btn',
'text': 'I agree',
'link': '/lesson/welcome/completed',
'color': '#e2574c'
},
2: {
'id': 2,
'type': 'btn',
'text': "I'm not sure I agree",
'link': '/contact',
'color': '#e2574c'
},
3: {
'id': 3,
'type': 'btn',
'text': 'I have a suggestion',
'link': '/contact',
'color': '#e2574c'
}
]
}
]
有什么建议可以实现吗?
或者,是否有更多的 Django 方法来实现这一点?
提前致谢
【问题讨论】:
-
你不是“追加[ing] json”;您正在附加到列表中。 JSON 是一种在文本中表示此类对象的符号。