我正在尝试将initial
(es_initial
)数据提供给我的formset
,其中initial
是一个词典列表。我的view.py有以下代码:
# get all answers by current student
es_answers_by_student = models.Answer.objects.filter(
student__user=request.user
).filter(
question__quiz=step
).filter(
eq_answer_text__icontains=''
)
# supply question prompt to the initial data
for es_question in eqs:
es_dict_for_initial.update({'question': es_question.prompt},)
es_initial.append(es_dict_for_initial.copy())
# supply saved answers
for answer in es_answers_by_student:
for _dict in es_initial:
_dict["eq_answer"] = answer.eq_answer_text
print(es_initial)
无法理解,为什么我的上一个for
循环始终返回相同的值,这是es_answers_by_student
queryset
修改
执行第一个for
循环后,es_initial
看起来像:
[{'question': 'question text 1'}, {'question': 'question text 2'}]
以下是我想在第二个for
循环后完成的事情:
[{'question': 'question text 1', 'eq_answer': 'answer text 1'},
{'question': 'question text 2', 'eq_answer': 'answer text 2'}]
答案 0 :(得分:1)
我认为您只想循环遍历_dict
,并在循环中更改答案,如下所示:
for _i, dict in enumerate(es_initial):
_dict["eq_answer"] = es_answers_by_student[i].eq_answer_text
这隐含地假设es_initial
和es_answers_by_student
的顺序是相同的,如果不是,你必须找到某种方法来索引es_answers_by_student
列表以找到正确的项目。