2016-01-15 50 views
0

所以我有了一个粗略的结构是这样一个会话变量:删除会话变量的Django

request.session['selected_courses'] = { 
    '2': {'num_spots_available': 3, 
      attendees = [ {'first_name': 'Jon', 'last_name': 'Kan'}, ... ]} 
    ... 
} 

每个按键下的“selected_courses”是课程ID。

我需要从所选课程中删除与会者i.e {'first_name': 'Jon', 'last_name': 'Kan'}当我尝试这样做时,会话实际上并未删除与会者。当我尝试删除另一位与会者时,即使我的代码先前已将其删除,以前的与会者也会立即弹出会议!但是,重新运行此代码后,它最终会从会话中删除与会者。

我在views.py代码(我拉出来的数据POST的,因为我在做一个AJAX请求,并知道数据是不是由用户输入):

course_id = str(request.POST['course_id']) 
first_name = str(request.POST['first_name']) 
last_name = str(request.POST['last_name']) 
request.session['selected_courses'][str(course_id)]['attendees'] = [a for a in request.session['selected_courses'][str(course_id)]['attendees'] 
     if a['first_name'] != first_name or a['last_name'] != last_name] 

request.session.modified =True 

所以我试图请求.session.modified属性(如上所示)与SESSION_SAVE_EVERY_REQUEST = True一起工作。 (请注意:我对Django仍然很陌生)。

回答

2

此代码是太复杂,至少有一个严重的错误。 remove不返回修改后的名单,但None,所以如果你做attendees = attendees.remove(...)则与会者现在没有了。

一个写这个代码将是与循环很简单的方法:

for course in request.session['selected_courses']: 
    if course['course_id'] == course_id: 
     course['attendees'] = [ 
      a for a in course['attendees'] 
      if a['first_name'] != first_name and a['last_name'] != last_name 
     ] 
     break 

注意,这不是任何低效的,因为你要mapremove电话是真的环本身。

或者,你可能会考虑不同的数据结构;如果你经常需要搜索selected_courses特定课程ID,倒不如将其存储为通过ID键的字典,而不是包含ID为值类型的字典列表。

request.session['selected_courses'] = { 
    '2': [ {'first_name': 'Jon', 'last_name': 'Kan'}, ... ] 
} 
+0

谢谢您的回答丹尼尔!是的,所以我尝试了你的解决方案,但它仍然没有删除与会者。我会尝试更改我的会话数据结构,并让您知道它是否仍然无效。 –