Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. from decimal import Decimal
  2. from django.conf import settings
  3. from shop.models import Product
  4.  
  5.  
  6. class Cart(object):
  7.     def __init__(self, request):
  8.         self.session = request.session
  9.         cart = self.session.get(settings.CART_SESSION_ID)
  10.         if not cart:
  11.             cart = self.session[settings.CART_SESSION_ID] = {}
  12.         self.cart = cart
  13.  
  14.     def add(self, product, quantity=1, update_quantity=False):
  15.         product_id = str(product.id)
  16.         if product_id not in self.cart:
  17.             self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
  18.         if update_quantity:
  19.             self.cart[product_id]['quantity'] = quantity
  20.         else:
  21.             self.cart[product_id]['quantity'] += quantity
  22.         self.save()
  23.  
  24.     def save(self):
  25.         self.session[settings.CART_SESSION_ID] = self.cart
  26.         self.session.modified = True
  27.  
  28.     def remove(self, product):
  29.         product_id = str(product.id)
  30.         if product_id in self.cart:
  31.             del self.cart[product_id]
  32.             self.save()
  33.  
  34.     def __iter__(self):
  35.         product_ids = self.cart.keys()
  36.         products = Product.objects.filter(id__in=product_ids)
  37.         for product in products:
  38.             self.cart[str(product.id)]['product'] = product
  39.  
  40.         for item in self.cart.values():
  41.             item['price'] = Decimal(item['price'])
  42.             item['total_price'] = item['price'] * item['quantity']
  43.             yield item
  44.  
  45.     def __len__(self):
  46.         return sum(item['quantity'] for item in self.cart.values())
  47.  
  48.     def get_total_price(self):
  49.         return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
  50.  
  51.     def clear(self):
  52.         del self.session[settings.CART_SESSION_ID]
  53.         self.session.modified = True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement