Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- from collections import OrderedDict
- from django.core.urlresolvers import reverse
- from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
- from .models import Product
- class CartItem:
- def __init__(self, product_pk, quantity):
- product = Product.objects.get(pk=product_pk)
- photo = product.productphoto_set.first()
- self.pk = product.pk
- self.url = reverse('product-detail', args=[product.category.slug, product.slug])
- self.name = product.name
- self.photo_url = photo.photo.url if photo else None
- self.price = product.sale_price if product.sale_price else product.price
- self.quantity = quantity
- self.subtotal_price = self.price*self.quantity
- @property
- def serializable(self):
- return self.__dict__
- class Cart:
- def __init__(self, session, session_key='cart'):
- self._session = session
- self._session_key = session_key
- if session_key in session:
- self._items = json.loads(session[session_key], object_pairs_hook=OrderedDict)
- else:
- self._items = OrderedDict()
- self.update_session()
- def change_quantity(self, product_pk, quantity_diff):
- if product_pk not in self._items:
- self._items[product_pk] = 0
- self._items[product_pk] += quantity_diff
- if self._items[product_pk] < 1:
- self.remove(product_pk)
- def remove(self, product_pk):
- self._items.pop(product_pk, None)
- def clear(self):
- self._items = OrderedDict()
- def update_session(self):
- self._session[self._session_key] = json.dumps(self._items)
- @property
- def items(self):
- for product_pk, quantity in self._items.items():
- try:
- yield CartItem(product_pk, quantity)
- except (ObjectDoesNotExist, MultipleObjectsReturned):
- pass
- @property
- def serializable(self):
- cart = {'items': [], 'total_quantity': 0, 'total_price': 0}
- for item in self.items:
- cart['items'].append(item.serializable)
- cart['total_quantity'] += item.quantity
- cart['total_price'] += item.subtotal_price
- return cart
Advertisement
Add Comment
Please, Sign In to add comment