I have following problems when trying to show the additional field of the 'trough table' of a many-to-many relationship templates. 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)
my templates:
{% for products in products %}
<p>{{products.productName}} |
{{products.price}} |
{{products.orderQuantity}}</p>
{% endfor %}
However, it can only list the product name and price, the orderQuantity is not showed in the webpage.
orderQuantity is a property of OrderItem, not of Product.
Try:
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
And in the template:
{% for item in order.items %}
<p>
{{ item.product.productName }} |
{{ item.product.price }} |
{{ item.orderQuantity }}
</p>
{% endfor %}
And maybe you want to change the models.CASCADE of the model, as this will cause to delete the product if the order is deleted.