【问题标题】:Render text from a dictionary/query in Django从 Django 中的字典/查询中渲染文本
【发布时间】:2019-09-07 11:40:35
【问题描述】:

当我将我的查询集渲染到我的 Django 模板上时,它会渲染整个查询集 带大括号。图片如下

我只需要字典的值而不是键。我不确定它是否正在打印,因为整个查询集是一个字符串。

在我看来,这是我的上下文,我将 2 个句子加入到一个列表中,然后尝试将它们呈现到模板中

 eng_sentance_flash = model.objects.filter(show_sentance = True).values('sentance_eng')[:1]  #limit 1
 esp_sentance_flash = model.objects.filter(show_sentance = True).values('sentance_esp')[:1]  
 zip_flash_sentances = list(zip(eng_sentance_flash,esp_sentance_flash))

 return render(request, template_name, {'sentances_list': user_sentances,'zip_flash_sentances':zip_flash_sentances})

这是我试图将其打印到屏幕上的代码

  {% for rand in zip_flash_sentances %}            
               <p>{{ rand.0 |safe }}</p> 
               <p>{{ rand.1 |safe }}</p>           

   {% endfor %}

屏幕上的输出是这样的

{'sentance_eng': 'Croagh Patrick is the sacred mountain of Ireland, where St. Patrick is supposed to fast for 44 days when he came to Christianize Ireland in the 5th century'}

{'sentance_esp': 'Croagh Patrick es la montaña sagrada de Irlanda, donde se supone que San Patricio ayunó durante 44 días cuando vino a cristianizar Irlanda en el siglo V'}

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    这些项目被包装在字典中,严格来说,您可以使用{{ rand.0.sentance_eng|safe }} 等解开这些项目。但是您可以通过在单个查询中查询两列来提高效率,将第一项解包出@987654323 @,并让Django使用.values_list(..) [Django-doc]进行压缩:

    zip_flash_sentances = model.objects.filter(
        show_sentance=True
    ).values_list('sentance_eng', 'stance_esp').first()
    
    return render(request, template_name, {'sentances_list': user_sentances,'zip_flash_sentances':zip_flash_sentances})

    .first() 将因此取出第一项,并将其从QuerySet 中解开。如果不存在这样的第一项,那么它将是None

    在模板中,您可以使用:

    <p>{{ zip_flash_sentances.0 |safe }}</p>
    <p>{{ zip_flash_sentances.1 |safe }}</p>

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 2014-08-25
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      相关资源
      最近更新 更多