2

使用时在模板中显示相关表的字段时遇到问题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)

我如何表示 和 中的相关字段OrdersProducts尤其是Customers在模板中。例如,我想显示Orders.invoice_number,Products.nameCustomer.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 %}
4

1 回答 1

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 %}
于 2014-01-16T04:13:52.780 回答