Question on Django: Displaying many to many fields

蹲街弑〆低调 提交于 2019-12-11 01:37:19

问题


I seem to have a problem with Django when it comes Rendering ManyToManyField in a template. I can make it work partially, but I cannot make it work properly as I want it.

Firstly I have an invoice template which displays Invoice details from my data base

#invoice_details.html
{% extends "base.html" %}

{% block content %}
<h2>Invoice Details</h2>
<div id="horizontalnav">
  <a href="/index/add_invoice">Add an Invoice</a>
  <a href="/index/work_orders">Add a Work Order</a>
  <a href="/index/add_payment">Add Payment</a>
</div>
<ul>
  <div id="list">
     {% for invoice in invoices_list %}
       {{invoice.client}}<br/>
       {{invoice.invoice_no}}<br/>
       {{invoice.contract_info}}<br/>
       {{invoice.date}}<br/>
       {{invoice.work_orders}}<br/>
     {% endfor %}
    </div>
</ul>
{% endblock %}

In my database, {{invoice.work_orders}} was displayed like the following below. This is because {{invoice.work_orders}} uses a manytomanyfield

<django.db.models.fields.related.ManyRelatedManager object at 0x8a811ec>

Now I tried to change {{invoice.work_orders}} to {{invoice.work_orders.all}} and I got this.

[<Work_Order: Assurance Support Service >]

This sort of works, but I want it to display "Assurance Support Service" only. So I am wondering how I can do this change if possible.


回答1:


The content of {{invoice.work_orders.all} is a list of Work_Order objects.
If you want to print them, you should iterate the list:

{% for invoice in invoice.work_orders.all %}
  {{invoice}}<br />
{% endfor %}


来源:https://stackoverflow.com/questions/3891321/question-on-django-displaying-many-to-many-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!