Django:在模板中显示多个到多个附加字段

时间:2017-04-21 22:46:07

标签: python django django-views many-to-many has-many-through

我在尝试显示“表格”的附加字段时遇到以下问题。多对多关系模板。 我的model.py:

class Product(models.Model):
  productName =  models.CharField(max_length=500)
  price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
  def __str__(self):
    return self.productName 
  def get_absolute_url(self):
    return reverse('itake:productList')

class Order(models.Model):
   orderID = models.CharField(max_length=100, blank=True, null=True)
   products = models.ManyToManyField(Product,related_name="order_item", through="OrderItem")
   def __str__(self):
      return self.orderID

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE,null=True)
    order = models.ForeignKey(Order,on_delete=models.CASCADE, null=True)
    orderQuantity = models.IntegerField(default=10)
    def __str__(self):
      return self.order.orderID + '-' +self.product.productName

my views.py:

def orderDetails(request,order_id):
    order = get_object_or_404(Order,pk=order_id)
    products = order.products.all()
    context = {'order': order,'products':products}
    return render(request, 'itake/orderDetails.html', context)

我的模板:

 {% for products in products %}
     <p>{{products.productName}} |
        {{products.price}} |
        {{products.orderQuantity}}</p>
  {% endfor %}

但是,它只能列出产品名称和价格,订单数量不会显示在网页上。

1 个答案:

答案 0 :(得分:1)

orderQuantity属于OrderItem,不属于Product

尝试:

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE,null=True)
    order = models.ForeignKey(Order,on_delete=models.CASCADE, null=True, related_name='items')
    orderQuantity = models.IntegerField(default=10)
    def __str__(self):
      return self.order.orderID + '-' +self.product.productName

在模板中:

{% for item in order.items %}
<p>
    {{ item.product.productName }} |
    {{ item.product.price }} |
    {{ item.orderQuantity }} 
</p>
{% endfor %}

也许您想要更改模型的models.CASCADE,因为如果订单被删除,这将导致删除产品。