如何在Django模板中迭代查询集字典

时间:2018-08-30 10:26:24

标签: django dictionary django-templates

这是我从视野中得到的字典:

{'questions_in_topic': <QuerySet [{'question_id__description': 'Describe your most significant leadership experience'}, {'questi
on_id__description': 'Which kind of leader are you?'}]>}

如何在Django模板中显示单个问题?

视图如下:

def get_question_from_topic(request):
    if request.method == "GET":
        questions_in_topic = QuestionTopic.objects.filter(topic_id=request.GET['topicId']).values('question_id__description').order_by('question_id__description')
        print(questions_in_topic)
        context = { 'questions_in_topic': questions_in_topic }
        print(context)
        return render(request, 'recruiter/add_question_library.html', context)
    return render(request, 'recruiter/add_question_library.html', context)

2 个答案:

答案 0 :(得分:1)

{% if questions_in_topic %}
{% for question in questions_in_topic %}
    Question: {{ question }}
{% endfor %}
{% endif %}

答案 1 :(得分:0)

如果您仅从查询集中访问一个字段,那么使用values_list可能更适合您的需求

更改

questions_in_topic = QuestionTopic.objects.filter(topic_id=request.GET['topicId']).values('question_id__description').order_by('question_id__description')

收件人

questions_in_topic = QuestionTopic.objects.filter(topic_id=request.GET['topicId']).order_by('question_id__description').values_list('question_id__description', flat=True)

questions_in_topic之后将是一个字符串列表。然后,您可以像这样在模板中使用它们

{% for question in questions_in_topic %}
    Question: {{ question }}
{% empty %}
    There are no questions.
{% endfor %}