简体   繁体   中英

How to sum two model fields together in Django

I am creating an eCommerce website and I am busy with the shopping cart at the moment. Currently I display product, quantity and order date. I would like to also display the order total for each order.

Currently my models look like this:

models.py

class Store(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=250)
    store_owner = models.ForeignKey(UserAccount, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class Product(models.Model):
    product_name = models.CharField(max_length=100)
    price = models.IntegerField(null=True, blank=True)
    description = models.TextField(max_length=250)
    store = models.ForeignKey(Store, on_delete=models.CASCADE)

    def __str__(self):
        return self.product_name


class Cart(models.Model):
    user = models.ForeignKey(UserAccount, on_delete=models.CASCADE)
    order_total = models.IntegerField(null=True, blank=True)
    checked_out = models.BooleanField(default=False)

    def __str__(self):
        return str(self.user)


class Order(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField(null=True, blank=True)
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    order_date = models.DateTimeField(auto_now=True)
    order_total = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return "{} order".format(self.product)

How do I add quantity and price together and assign it to order_total? I also can't figure out how to assign it dynamically because each user would have a different total.

I have looked at Django: Calculate the Sum of the column values through query but I can't figure out how to apply it to my models.

Any suggestions?

You can override you save method in your model Cart.

def save(self, *args, **kwargs):
    if not self.id:
      super(Model, self).save(*args, **kwargs)
    else:
      total = 0.0 # should be DecimalField not integer or float for prices
      for item in Order.objects.filter(cart=self.id):
        total += (item.quantity * item.product.price)
      self.order_total = total # again this should be changed to DecimalField
    super(Model, self).save(*args, **kwargs)

or if you would have price withour foreign key as product this query might do the trick

def save(self, *args, **kwargs):
    if not self.id:
      super(Model, self).save(*args, **kwargs)
    else:
      total = Order.objects.filter(cart=self.id).aggregate(
            total=Sum('price', field="price*quantity")
         )['total']
      self.order_total = total
    super(Model, self).save(*args, **kwargs)

You do not mention in which context you need this, but the simplest I can think of would be:

# order is class 'Order'
order.order_total = order.product.price * order.quantity
order.save()

Note that this will fail if either of product , price or quantity are None .


In case you ment the field on the Cart class:

# cart is class 'Cart'
cart.order_total = sum(
    order.order_total
    for order in cart.order_set.all())
cart.save()

Note that this will also fail if order.order_total is None .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM