Reputation: 881
How can i get "total" price of items of OrderItem in cart model from these models down below? I tried doing something in views but I get attribute error that QuerySet' object has no attribute 'total'.
views.py
def cart(request):
cart = Cart.objects.filter(order_user=request.user)
order_items = OrderItem.objects.filter(cart__in=cart)
total = 0
for i in order_items:
total = i.quantity * i.item.price + cart.total
cart.update(total=total)
models.py
class OrderItem(models.Model):
cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True)
item = models.ForeignKey(Item, on_delete=CASCADE, null=True)
quantity = models.IntegerField(default=1)
class Item(Visits, models.Model):
title = models.CharField(max_length=150)
price = models.IntegerField(default=1000)
image = models.ImageField(upload_to='pictures', default='static/images/man.png')
description = models.TextField(default="Item")
visits = models.IntegerField(default=0)
class Cart(models.Model):
order_user = models.OneToOneField(User, on_delete=CASCADE)
ordered = models.BooleanField(default=False)
total = models.IntegerField(default=0, help_text="100 = 1EUR")
order_items = models.ManyToManyField(Item, related_name='carts', through=OrderItem )
Upvotes: 0
Views: 166
Reputation: 2613
Just aggregate the total of ModelField total
of the queryset like so
Total = Cart.objects.all().aggregate('total')
# Filtered in your case
Total = Cart.objects.filter(order_user=request.user).aggregate('total')
Apply filtering as necessary. Also I suggest to have a good read here
Upvotes: 2
Reputation: 75
You can retrieve the cart information for current users via the OrderItem model itself.
Check how annotate works
from django.db.models import Count
order_items = (OrderItem.objects.filter(cart__order_user=request.user)
.annotate(total=Count("quantity")*(item__price) + cart__total)
)
Upvotes: 0