1、问卷:
如果获取的数据不是直接可以展示的结构(共有三种方法)
方式一:循环一次,生成数据 user_list = [ {'id':1,'name':'alex','age':19}, {'id':2,'name':'eric','age':18}, ] new_user_list = [] for item in user_list: item["age"] = item["id"]+item["age"] new_user_list.append(item["age"]) return render(request,'test.html',{'user_list':new_user_list})
方式二:利用yield来实现 def test(request): user_list = [ {'id':1,'name':'alex','age':19}, {'id':2,'name':'eric','age':18}, ] def inner(arg): for item in arg: yield {'id':item['id'], 'name':item['name'],'age':item['id']+item['age']} return render(request,'test.html',{'user_list':inner(user_list)})
方式三:利用类,__item__、yield来实现 class Foo(object): def __init__(self,data): self.data = data def __iter__(self): for item in self.data: yield item def test(request): user_list = [ {'id':1,'name':'alex','age':19}, {'id':2,'name':'eric','age':18}, ] obj = Foo(user_list) return render(request,'test.html',{'user_list':obj})