使用select_related()
这是我的模特:
class Customer(models.model):
customer_name = models.CharField(max_length=500)
class Orders(models.model):
cust_id = models.ForeignKey(Customers)
invoice_number = models.IntegerField()
invoice_creation_date = models.DateTimeField('Invoice Created Date')
class Products(models.Model):
name = models.CharField(max_length=500)
description = models.CharField(max_length=500)
price = models.DecimalField(max_digits=20, decimal_places=2)
class Orders_Products(models.Model):
order_id = models.ForeignKey(Orders)
product_id = models.ForeignKey(Products)
quantity = models.IntegerField(default=0)
以下是我的观点:
def home(request):
list_of_orders = Orders_Products.objects.select_related()
template = 'erp_app/home.html'
context = RequestContext(request, {'list_of_orders': list_of_orders})
return render(request, template, context)
如何在模板中表示来自Orders
和Products
的相关字段,尤其是Customers
。例如。我想在相同的相关记录中显示Orders.invoice_number
,Products.name
和Customer.customer_name
。
例如:
{% for order in list_of_orders %}
<tr>
<td>{{ order.orders.invoice_number }}</td>
<td>{{ order.products.name }}</td>
<td>{{ order.customers.customer_name }}</td>
</tr>
{% endfor %}
答案 0 :(得分:7)
我明白了。我要离开这个问题并在这里回答下一个不得不通过这个难题解决问题的可怜人。
{% for order in list_of_orders %}
<tr>
<td>{{ order.order_id.cust_id.customer_name }}</td>
<td>{{ order.order_id.invoice_number }}</td>
<td>{{ order.order_id.invoice_creation_date }}</td>
<td>{{ order.product_id.price }}</td>
</tr>
{% endfor %}