How to design shopping basket using session?

user1836831 picture user1836831 · Nov 19, 2012 · Viewed 8.4k times · Source
class Product(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField()
    unit_price = models.DecimalField(max_digits=5, decimal_places=2)

I'am newbie to Django. How to design shopping basket using session? (ask for a general "algorithm" or some example code)

Answer

JoseP picture JoseP · Nov 20, 2012

I wouldn't use a model. You can store the values directly in the session. Considering that you can store everything in the session you can store the items in a dictionary do something like.

def view_cart(request):
    cart = request.session.get('cart', {})
    # rest of the view

def add_to_cart(request, item_id, quantity):
    cart = request.session.get('cart', {})
    cart[item_id] = quantity
    request.session['cart'] = cart
    # rest of the view