Reputation: 1658
I am trying modify session and store a list of model objects.
This is my view-
def update_cart(request):
if request.method == 'POST':
post = request.POST
cart = json.loads(post['cart'])
food_list = []
for f in cart['food']:
food_list.append(Food.objects.get(food_id = f))
print food_list
request.session['food'] = food_list
request.session.modified = True
request.session['quantity'] = cart['quantity']
request.session['price'] = cart['price']
request.session['amount'] = cart['amount']
print request.session
return JsonResponse({'data': 'OK'})
It is printing the food_list and the session object as <django.contrib.sessions.backends.db.SessionStore object at 0x7f49bca6e150>
After this I am getting internal server error.
I also have SESSION_SAVE_EVERY_REQUEST = True
in my settings
Still I am unable to do it.
Any help is appreciated.
Upvotes: 2
Views: 4583
Reputation: 1986
Session wants something which is JSON serializable. So you have to adjust the following rule food_list.append(Food.objects.get(food_id = f))
into append ids.
You could change the construction of the list into the following line. Also changes multiple gets on the DB into one filter.
food_list = [f.id for f in Food.objects.filter(food_id__in=cart['food'])]
Upvotes: 2