Guest User

Shopping cart implementation for Django

a guest
Dec 7th, 2014
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. import json
  2. from collections import OrderedDict
  3. from django.core.urlresolvers import reverse
  4. from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
  5. from .models import Product
  6.  
  7.  
  8. class CartItem:
  9.     def __init__(self, product_pk, quantity):
  10.         product = Product.objects.get(pk=product_pk)
  11.         photo = product.productphoto_set.first()
  12.         self.pk = product.pk
  13.         self.url = reverse('product-detail', args=[product.category.slug, product.slug])
  14.         self.name = product.name
  15.         self.photo_url = photo.photo.url if photo else None
  16.         self.price = product.sale_price if product.sale_price else product.price
  17.         self.quantity = quantity
  18.         self.subtotal_price = self.price*self.quantity
  19.  
  20.     @property
  21.     def serializable(self):
  22.         return self.__dict__
  23.  
  24.  
  25. class Cart:
  26.     def __init__(self, session, session_key='cart'):
  27.         self._session = session
  28.         self._session_key = session_key
  29.         if session_key in session:
  30.             self._items = json.loads(session[session_key], object_pairs_hook=OrderedDict)
  31.         else:
  32.             self._items = OrderedDict()
  33.             self.update_session()
  34.  
  35.     def change_quantity(self, product_pk, quantity_diff):
  36.         if product_pk not in self._items:
  37.             self._items[product_pk] = 0
  38.         self._items[product_pk] += quantity_diff
  39.         if self._items[product_pk] < 1:
  40.             self.remove(product_pk)
  41.  
  42.     def remove(self, product_pk):
  43.         self._items.pop(product_pk, None)
  44.  
  45.     def clear(self):
  46.         self._items = OrderedDict()
  47.  
  48.     def update_session(self):
  49.         self._session[self._session_key] = json.dumps(self._items)
  50.  
  51.     @property
  52.     def items(self):
  53.         for product_pk, quantity in self._items.items():
  54.             try:
  55.                 yield CartItem(product_pk, quantity)
  56.             except (ObjectDoesNotExist, MultipleObjectsReturned):
  57.                 pass
  58.  
  59.     @property
  60.     def serializable(self):
  61.         cart = {'items': [], 'total_quantity': 0, 'total_price': 0}
  62.         for item in self.items:
  63.             cart['items'].append(item.serializable)
  64.             cart['total_quantity'] += item.quantity
  65.             cart['total_price'] += item.subtotal_price
  66.         return cart
Advertisement
Add Comment
Please, Sign In to add comment