假设我使用循环生成变量列表或字典:
a = {}
b = []
k = 1
count = TaskBox.objects.all().count()
output = ""
while k <= count:
ck = str(k)
newline = output.join("box"+ck+" = InboxEntry.objects.filter(box="+ck+")")
c.append(newline)
b['box'+ck] = "InboxEntry.objects.filter(box="+ck+")"
k += 1
产生:['box1 = InboxEntry.objects.filter(box = 1)','box2 = InboxEntry.objects.filter(box = 2)']
和 {'box2':'InboxEntry.objects.filter(box = 2)','box1':'InboxEntry.objects.filter(box = 1)'}
如何解压缩任何结构中的变量以便在views.py?
中使用我最终会寻找类似的东西:
def display_prdInboxEntry(request, id):
if request.method == 'POST':
form = PrdInboxForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('taskmanager/display/'+ id +'/')
else:
form = PrdInboxForm(request.POST)
return HttpResponseRedirect('taskmanager/display/'+ id +'/')
else:
form = PrdInboxForm()
user = request.user
u = UserProfile.objects.get(pk=id)
boxrecords = TaskBox.objects.all()
assignedrecords = InboxEntry.objects.filter(assigned_by=u)
'''loop code'''
a = {}
b = []
k = 1
count = TaskBox.objects.all().count()
output = ""
while k <= count:
ck = str(k)
newline = output.join("box"+ck+" = InboxEntry.objects.filter(box="+ck+")")
c.append(newline)
b['box'+ck] = "InboxEntry.objects.filter(box="+ck+")"
k += 1
'''need to pull these values from the product of the loop'''
box1 = InboxEntry.objects.filter(box=1)
box2 = InboxEntry.objects.filter(box=2)
records = InboxEntry.objects.filter(assigned_to=u).order_by('status')
return render_to_response('taskmanager/taskmanager_view.html', {'form': form, 'assignedrecords': assignedrecords, 'records': records, 'boxrecords': boxrecords, 'box1' : box1, 'box2' : box2, 'user': user}, context_instance=RequestContext(request))
答案 0 :(得分:0)
def display_prdInboxEntry(request, id):
if request.method == 'POST':
'''form code'''
else:
form = PrdInboxForm()
user = request.user
u = UserProfile.objects.get(pk=id)
assignedrecords = InboxEntry.objects.filter(assigned_by=u)
records = InboxEntry.objects.filter(assigned_to=u).order_by('status')
boxrecords = TaskBox.objects.all()
boxes = TaskBox.objects.all().count()
''' variable generator'''
boxdict = {}
for x in range(1, boxes + 1):
boxdict['box{0}s'.format(x)] = InboxEntry.objects.filter(box='{0}'.format(x))
returndict = {'form': form, 'assignedrecords': assignedrecords, 'records': records, 'boxrecords': boxrecords, 'user': user}
''' return dictionary concatenation'''
z = returndict.copy()
z.update(boxdict)
return render_to_response('taskmanager/taskmanager_view.html', z, context_instance=RequestContext(request))
不知道它是多么传统,并且对模板进行有效编码将是一个挑战 - 但它有效,并且允许用户在管理中即时创建任务框,而无需适应视图代码 - 这就是我所追求的。