'How to get related ManyToMany objects from different model and render them in HTML format?
I tried to look up the order class and get the last 5 orders with their customer and items. But got the following exception:
*Exception Type: ValueError
Exception Value:
Negative indexing is not supported.*
Here are the models:
class Customer(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class Order(models.Model):
placed_at = models.DateTimeField(auto_now_add=True)
customer = models.ForeignKey(Customer, on_delete=models.PROTECT)
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.PROTECT)
product = models.ForeignKey(Product, on_delete=models.PROTECT)
And here is the view class:
def last_5_orders(request):
orders = Order.objects.select_related('customer').prefetch_related('orderitem_set__product').order_by('placed_at')[-5:]
return render(request, 'last_5_orders.html', {'orders': orders})
And finally in last_5_orders.html file I have:
{% for order in orders %}
<h1>
{{ order.id }} : {{ order.custumer.first_name }} {{ order.custumer.last_name }} PURCHASED {{order.orderitem_set.product}}
</h1>
{% endfor %}
Any ideas about resolving this issue?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
