Reputation: 475
I'm trying to implement a simple cart using a dictionary
{item_id:qty}
@dajaxice_register
def inc_items(request, item_id):
item_id=int(item_id)
print "ITEMID: ", item_id
#cart is a list of items {(id:qty)}
dajax=Dajax()
if 'cart' not in request.session :
request.session['cart']={}
cart = request.session['cart']
if item_id not in cart:
cart[item_id]=0
cart[item_id] += 1
print "CART:", cart
request.session['cart']=cart
request.session.modified = True
request.session.save()
count=sum(cart.values())
dajax.assign('#cart_items', 'innerHTML', str(count))
I tried using request.session.modified as noted in the documentation no matter what, i receive a very weird result
CART: {u'1': 1, 1: 1, u'3': 1, u'2': 1}
note: I explicitly cast the item_id to integer, so I don't know where the string keys came from!
note: the cart object doesn't hold more than 4 keys also!
Thanks in advance
Upvotes: 2
Views: 506
Reputation: 53729
The default serialization used by sessions is the JSON format. JSON only allows strings as keys, so when the data is saved to the database, all integer keys are converted to strings. When you load the data, the fact that they were integers is lost, and the keys are plain strings (well, unicode strings).
The simplest solution is to specifically use strings in your session data keys, and only convert them to integers for further processing.
Upvotes: 4