我有三个模特:
Book
,Topiccenter
和EntryBook
。
这些是模型定义:
class Book(models.Model):
title = models.TextField()
language = models.TextField()
class Topiccenter(models.Model):
title = models.TextField():
description = models.TextField()
class EntryBook(models.Model):
book = models.ForeignKey(Book,related_name="b_entries")
topiccenter = models.ForeignKey(Topiccenter,related_name="tc_books")
现在我在主题中心T
。我搜索书籍,把所有的书都放在DB里。正如您所看到的,每本书都可以位于多个主题中心。
我想要做的是,在搜索结果中,显示每本书是否包含在当前的主题中心中:
我将把所有书籍books = Book.objects.all()
和当前主题中心作为tc
,并将它们呈现为模板和模板,
{% for book in books %}
{% for entry in book.b_entries.all %}
{% if entry.topiccenter.id == tc.id %}
already in this Topiccenter
{% else %}
add to this topiccenter
{% endif %}
{% endfor %}
{% endfor %}
但问题是,一本书位于两个主题中心,而在模板中,我得到的是already in this Topiccenter
和add to this topiccenter
,这是不可靠的。我如何修复我的逻辑,以便我可以检查书是否在这个当前的主题中心,如果没有,显示他们add
按钮。
谢谢
发布于 2013-11-13 17:42:30
看看如何将它移到视图中。在本例中,获取与tc
相关的所有书籍并在上下文中发送。
现在,模板逻辑应该是:
{% for book in books %}
{% if book in tc_books %}
already in this Topiccenter
{% else %}
add to this topiccenter
{% endif %}
{% endfor %}
(在视图中)
tc_books = Books.objects.filter(b_entries__topiccenter = tc)
并在上下文中发送
https://stackoverflow.com/questions/19960553
复制相似问题