Python Django:在模板中显示多对多附加字段

Python Django:在模板中显示多对多附加字段,python,django,django-views,many-to-many,has-many-through,Python,Django,Django Views,Many To Many,Has Many Through,在尝试显示多对多关系模板的“槽表”的附加字段时,我遇到以下问题。 my 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.pr

在尝试显示多对多关系模板的“槽表”的附加字段时,我遇到以下问题。 my 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 %}
{%用于产品%中的产品]
{{products.productName}|
{{products.price}}|
{{products.orderQuantity}

{%endfor%}

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

orderQuantity
OrderItem
的属性,而不是
产品的属性

尝试:

在模板中:

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

{{item.product.productName}|
{{item.product.price}}|
{{item.orderQuantity}

{%endfor%}
您可能需要更改模型的
models.CASCADE
,因为如果订单被删除,这将导致删除产品

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