显示多对多字段

时间:2010-10-29 15:04:40

标签: django django-templates many-to-many django-views manytomanyfield

我似乎在显示工单时遇到问题。在我的应用程序中客户没有相同的问题,为什么工作订单不显示。实际上它几乎就像出现在我的数据库中的黑色空间而不是文本。

问题似乎是因为工作单具有多对多字段。如果我有{{work_orders}}而不是说'{{work_orders.description}},我会得到这个

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

以下是我的应用程序的一些输出。

#views
@login_required 
def invoice_details(request, id=1):
    invoices_list = Invoice.objects.filter(pk=id) 
    client = invoices_list[0].client
    work_orders = invoices_list[0].work_orders
    return render_to_response(('invoice_details.html', locals()), {'work_orders': work_orders,'client': client, 'invoices_list': invoices_list}, context_instance=RequestContext(request))

#models.py
class Invoice(models.Model):
    client = models.ForeignKey(Client)
    date = models.DateField()
    invoice_no = models.CharField(max_length=16)
    work_orders = models.ManyToManyField(Work_Order)
    contract_info = models.ForeignKey(Contract_Info)

    def __unicode__(self):
                    return self.invoice_no

#invoice_details.html
   {{client.company}}<br/>
   {{client.address}}<br/>
   {{client.city}}<br/>
   {{client.postcode}}<br/>

   {{work_orders.description}}<br/>
   {{work_orders.quantity}}<br/>
   {{work_orders.item_no}}<br/>

2 个答案:

答案 0 :(得分:2)

不应该是work_orders.all,例如

{% for work_order in work_orders.all %}
  {{work_order.description}}
{% endfor %}

答案 1 :(得分:0)

#views
from django.shortcuts import get_object_or_404
@login_required 
def invoice_details(request, id=1):
    invoice = get_object_or_404(Invoice, pk=id) 
    return render_to_response(('invoice_details.html', locals()), {'invoice': invoice}, context_instance=RequestContext(request))

#models.py
class Invoice(models.Model):
    client = models.ForeignKey(Client)
    date = models.DateField()
    invoice_no = models.CharField(max_length=16)
    work_orders = models.ManyToManyField(Work_Order)
    contract_info = models.ForeignKey(Contract_Info)

    def __unicode__(self):
                    return self.invoice_no

#invoice_details.html
   {{ invoice.client.company }}<br/>
   {{ invoice.client.address }}<br/>
   {{ invoice.client.city }}<br/>
   {{ invoice.client.postcode }}<br/>

   {% for work_order in invoice.work_orders.all %}
     {{ work_order.description }}<br/>
     {{ work_order.quantity }}<br/>
     {{ work_order.item_no }}<br/>
   {% endfor %}