新手刚刚学习,两张表,多对多数据, 一张老师表(字段: id,name),一张班级表(字段:id,caption), 老师表中通过 cls = models.ManyToManyField('Classes') 关联班级表,同一个老师下面的不同的班级作为一个数组字典(字段:cls_list)封装; 代码贴在下面,感觉明显累赘了,求优雅的写法...
teacher_list = models.Teacher.objects.values('id', 'name', 'cls__id', 'cls__caption')
data = []
for t in teacher_list:
if len(data) == 0:
t = teacher_list.first()
data.append({
'nid': t['id'],
'name': t['name'],
'cls_list': [
{'id': t['cls__id'], 'caption': t['cls__caption']}
]
})
else:
for i, v in enumerate(data):
if t['id'] == v['nid']:
data[i]['cls_list'].append({'id': t['cls__id'], 'caption': t['cls__caption']})
elif i == len(data)-1:
data.append({
'nid': t['id'],
'name': t['name'],
'cls_list': [
{'id': t['cls__id'], 'caption': t['cls__caption']}
]
})
response = json.dumps({'data': data})
return HttpResponse(response)