uche
uche

Reputation: 85

Django - Cannot resolve keyword 'total' into field

Am having a model called Cart which contains the following fields

class Cart(models.Model):
    client = models.ForeignKey(User, null=True)
    description = models.CharField(max_length = 100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.PositiveIntegerField()
    ordered = models.BooleanField(default=False)
    created_on = models.DateTimeField(auto_now_add = True)

    def __str__(self):
        return self.description

    def total(self):
        return self.price * self.quantity 

I wish to get the total amount per item in django views.

Here is the cart views

def cart(request):    # Client View
    request_user = request.user

    item = Cart.objects.filter(client=request_user, ordered=False).values('total')
    print "item ", item

If i print item, i get Cannot resolve keyword 'total' into field. Choices are: client, client_id, created_on, description, docfile, id, order_id, ordered, price, quantity

But if i print item when .value('price'), i get result.

Is there a way to get value of total amount

Upvotes: 0

Views: 932

Answers (2)

Piyush S. Wanare
Piyush S. Wanare

Reputation: 4933

You need to create total function which will take price of each object you filter on the basis of client OR you can right query as follows:

total = 0

    for i in Cart.objects.filter(client=request_user, ordered=False).all():
        #print i.price
        total = total+i.price

You can't write values('total'), as you don't have any field in your card model as total.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

Why don't you try this? ie, access the total method through Cart instance.

[i.total() for i in Cart.objects.filter(client=request_user, ordered=False)]

Upvotes: 1

Related Questions