【问题标题】:Get the value in queryset in Django template在 Django 模板中获取查询集中的值
【发布时间】:2021-09-20 07:04:24
【问题描述】:

我使用 Django 开发了一个网络应用程序。 在 View 函数中,我向前端呈现了一个查询集列表。 在我的例子中,标题表是书籍信息,材料是这本书的详细信息附加到哪个课程,如果这个附加关系是“丢弃”。 is_discard 在 Material 表中,而不是书籍是否丢弃。在 Material 表中,一个课程附加了几本书,并且丢弃状态不是按书籍而是按书籍-课程对,因为有些书籍可能在一个课程中丢弃但在其他课程中有效

view.py:

def render_2(request):
    books = Title.objects.filter(name=title).values()
    query_results_book_is_discard = 
    Material.objects.filter(id=book_id).values('is_discard')
    return render(request, 'main.html',
                              context= 
    {'query_results_book_is_discard':query_results_book_is_discard, 
      'book', books})

在前端,query_results_book_is_discard 变量显示如下格式:

<QuerySet [{'is_discard': True}, {'is_discard': False}, {'is_discard': False}, {'is_discard': False}, {'is_discard': True}, {'is_discard': True}, {'is_discard': False}]> 

query_results_book_is_discard 变量在前端 Django 模板的循环中, 我想使用 forloop 计数器来获取值(True 或 False)以使用 if 条件进行检查。 我已经在 main.html 中尝试过:

  {% for book in books %}
     {% if query_results_book_is_discard.counter0 != False %}
 ...

{% if query_results_book_is_discard.counter0.is_discard != False %}

 {% if query_results_book_is_discard.is_discard.counter0 != False %}

全部失败。

如何获取 query_results_book_is_discard 中的 True 或 False 值以使用 if 条件?

【问题讨论】:

标签: django django-templates django-queryset django-template-filters


【解决方案1】:

我建议您创建一个custom template tag,允许您访问模板中列表的特定索引,如下所示。

你的应用文件树结构应该是这样的:

your_app/
    __init__.py
    models.py
    templatetags/
        __init__.py
        your_app_extras.py
    views.py

然后,在您的自定义模板标记文件中。

your_app_extras.py

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

然后,在您的模板中,加载您的自定义模板标签:

{% load your_app_extras %}

然后,在您的 for 循环中,您使用以下内容:

{% for book in books %}
    {% with query_results_book=query_results_book_is_discard|index:forloop.counter0 %}
        {% if query_results_book.is_discard %}
    {% endwith %}
{% endfor %}

【讨论】:

  • 我已经有一个循环 {% for book in books %} 。 query_results_book_is_discard 是另一个表,仅包含丢弃信息和书籍 ID,但没有任何书籍信息。这里我必须使用for循环的计数器,而不是编写另一个forloop。
  • @Django 你能分享更多你的代码以便我们更好看吗?
  • 已更新,在我的情况下,is_discard 在另一个表中,而不是书籍丢弃与否。在另一个表中,几本书附加到一个课程中,丢弃状态不是按书籍而是按书籍-课程对,因为有些书籍可能在一个课程中丢弃但在其他课程中有效
  • 如何在 query_results_book_is_discard 中获取 is_discard 值? query_results_book_is_discard 是这样的:
  • (query_results_book_is_discard|index:forloop.counter0).is_discard ?
猜你喜欢
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 2019-03-09
  • 1970-01-01
  • 2020-06-09
  • 2020-09-12
  • 2018-12-04
相关资源
最近更新 更多