我怎么能在Django模板中这样做

don*_*yor 1 python django django-templates

我想在django模板中这样做:

{% for book in books %}
  if book in this library
       print "already in this library"
  else
       print "add to this library"
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

有两个库LO.

但同一本书可以在多个图书馆,我在图书馆L.这本书b在两个图书馆.这就是为什么我的循环给出两个输出.

already in this library
add to this library
Run Code Online (Sandbox Code Playgroud)

这是胡说八道.我该如何修复这个逻辑?

Ash*_*han 5

所以有两种情况:

  • a)书在某个图书馆
  • b)书不在任何图书馆

我的建议是在视图级别而不是在模板级别执行此操作:

  1. 编写一个计算两个列表的视图函数:一个不在库中的书籍,另一个在某个库中的书籍.
  2. 将这两个数组合并到一个字典中(key = book name,value = boolean value,指示该书是否在库中)
  3. 将该字典发送到模板