簡體   English   中英

比較來自多個查詢的Django-taggit標簽,並列出匹配標簽中的對象

[英]Compare Django-taggit tags from multiple queries and list objects from matching tags

我有一個出售零件和工具的網站。 該站點最初是用單獨的工具模型和這些工具的文檔構建的。 文檔只是在文檔頁面上迭代,並從工具頁面鏈接到。 我們使用Django-taggit標記所有內容,但我已將自己標記在角落:)

我需要在工具詳細信息頁面而不是單獨的文檔頁面上列出屬於特定工具的文檔。

問題是與該工具的文檔沒有任何關系,因此我試圖查詢該工具上的標簽以及該文檔上的標簽以及與該工具具有相同標簽的任何文檔,都將在頁面上列出。

以下是我到目前為止提出的內容,它在某種意義上與標簽匹配,但是它會復制每個文檔。 例如,如果我在工具和文檔上都具有標簽名“一個”和“兩個”,它將列出所有匹配的文檔乘以匹配的標簽數。 我希望這是有道理的。我還提供了一個截圖以顯示示例。 我知道為什么我的代碼是重復的,但是我的Python印章不夠熟練,無法編寫解決它的代碼(我也知道這可以寫得更干-這是我的下一個挑戰)。 謝謝您的幫助。

在此處輸入圖片說明

視圖

def tool_detail(request, tool):
  contact_form(ContactForm, request)
  tags = Tool.tags.all()
  tool = get_object_or_404(Tool, slug=tool)
  uploads = tool.uploads.all()
  doc = Document.objects.all()
  return render(request, 'products/tool_detail.html', {'tool': tool, 'tags': tags, 'doc': doc, 'form': ContactForm, 'uploads': uploads})

模板

...
<tbody>
  {% for d in doc %}
    {% for tag in tool.tags.all %}
        {% if tag.name in d.tags.get.name %}
           <tr>
             <td>{{ d.title }}</td>
             <td style="text-align: center;"><a href="{{ d.file.url }}"><i class="fa fa-cloud-download"></i></a></td>
           </tr>
       {% endif %}
    {% endfor %}
 {% endfor %}
</tbody>
...

首先,將業務邏輯放在模板中是一種不好的做法-應該在視圖中完成。 話雖如此,關於您的問題。 首先-視圖(請參見代碼中的注釋):

def tool_detail(request, tool):
    contact_form(ContactForm, request)
    tags = Tool.tags.all()
    tool = get_object_or_404(Tool, slug=tool)
    uploads = tool.uploads.all()
    # filter the documents to find the ones that have identical tags,
    # add .distinct() to filter out duplicate documents
    doc = Document.objects.filter(tags__in=tool.tags.all()).distinct()
    return render(request, 'products/tool_detail.html', {'tool': tool, 'tags': tags,  'doc': doc, 'form': ContactForm, 'uploads': uploads})

形式就是:

...
<tbody>
    {% for d in doc %}
        <tr>
            <td>{{ d.title }}</td>
                <td style="text-align: center;"><a href="{{ d.file.url }}"><i class="fa fa-cloud-download"></i></a>
            </td>
        </tr>
    {% endfor %}
</tbody>
...

文檔中閱讀有關過濾和字段查找的更多信息。

暫無
暫無

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

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