Django e-commerce part46 Cart SubTotal
cartのsubtotalを表示する。
carts/models.py に追記
subtotal fieldを追加。subtotalのアップデートfunctionを追記する。
class Cart(models.Model): ... subtotal = models.DecimalField(max_digits=50, decimal_places=0, null=True, blank=True) def __str__(self): return str(self.id) def update_subtotal(self): for item in self.items.all(): subtotal += item.line_item_total self.subtotal = subtotal self.save()
post_saveを追記する
CartItemが、saveされた後に、Cart().subtotal()を実行する。
from django.db.models.signals import pre_save, post_save ... def cart_item_pre_save_receiver(sender, instance, *args, **kwargs): qty = instance.quantity if int(qty) >= 1: price = instance.item.get_price() line_item_total = Decimal(qty) * Decimal(price) instance.line_item_total = line_item_total pre_save.connect(cart_item_pre_save_receiver, sender=CartItem) def cart_item_post_save_receiver(sender, instance, *args, **kwargs): instance.cart.update_subtotal() post_save.connect(cart_item_post_save_receiver, sender=CartItem)
view.html にsubtotalを追記する。
<td colspan='4' class='text-right'>Subtotal: {{ object.subtotal }}</td>
models.py のupdateの箇所をちょっと間違えていたので、修正する。
items.all →これは意味をなさない cartitem_set.all()に修正する。
def update_subtotal(self): subtotal = 0 items = self.cartitem_set.all() for item in items: subtotal += item.line_item_total self.subtotal = subtotal self.save()