外键 - 如何在模板中解决这个问题 - django

时间:2013-11-13 17:35:10

标签: python django django-templates

我有3个型号:

BookTopiccenterEntryBook

这些是模型定义:

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")

现在我在Topiccenter T。我搜索书籍并获得DB中的所有书籍。如您所见,每本书都可以在多个主题中心。

我想要做的是,在搜索结果中,我想显示每本书是否包含在当前的Topiccenter中:

我会将所有图书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 Topiccenteradd to this topiccenter都是无意义的。我如何修复我的逻辑,以便我可以检查当前topiccenter中的书,如果没有,则显示它们add按钮

感谢

1 个答案:

答案 0 :(得分:2)

了解如何将其移至视图中。在这种情况下,获取与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)

并在上下文中发送