0

私はパーツとツールを販売するサイトを持っています。このサイトはもともと、これらのツール用のツールとドキュメントのための別々のモデルで構築されていました。ドキュメントは、ドキュメントページ上で反復され、ツールページからリンクされました。私たちはDjango-taggitを使ってすべてをタグ付けしますが、私はコーナーに自分自身をタグ付けしています:)複数のクエリのDjango-taggitタグと一致するタグのオブジェクトを比較

特定のツールに属するドキュメントを、ツールの詳細ページに表示する必要があります。

問題は、ドキュメントとの関係がないため、ツール上のタグとドキュメント上のタグ、およびツールと同じタグを持つドキュメントを照会しようとしています。ページ上に

以下は私がこれまで出てきたものであり、タグと一致する意味では機能しますが、すべてのドキュメントが重複しています。たとえば、ツールとドキュメントの両方に「1」と「2」というタグ名がある場合、一致するすべてのドキュメントに一致するタグの数を掛けたものがリストされます。私は意味があることを願って...私はまた例を示すスクリーンショットを含んだ。なぜ私のコードが重複しているのか知っていますが、私のPythonチョップはそれを解決するのに必要なコードを書くほどの味ではありません(私はこれもドライヤーに書き込むことができます - それは私の次の課題です)。ご協力ありがとうございました。すべての

enter image description here

ビュー

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> 
... 

答えて

1

まず、それがテンプレートにビジネスロジックを置く悪い習慣だ - それはビューで行う必要があります。あなたの質問に、それを言った。まず - ビュー(コード内のコメントを参照してください):

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> 
... 

documentationでフィルタリングし、フィールドのルックアップについては、こちらをご覧ください。

+0

ダングそれ、私はそれを逃したのですか? :)ありがとう、またはあなたの助け! –

関連する問題