簡體   English   中英

外鍵 - 如何在模板中解決這個問題 - django

[英]Foreign Key - how to solve this in template - django

我有3個型號:

BookTopiccenterEntryBook Book

這些是模型定義:

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()和當前的topiccenter作為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 ,這是無意義的。 我如何修復我的邏輯,以便我可以檢查當前topiccenter中的書,如果沒有,則顯示它們add按鈕

謝謝

了解如何將其移動到視圖中。 在這種情況下,獲取與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)

並在上下文中發送

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM