V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
whajcf
V2EX  ›  Python

求助 列表筛选问题 重复数据 组合 并封装成列表 返回前端的操作

  •  
  •   whajcf · 2017-11-28 16:42:43 +08:00 · 1433 次点击
    这是一个创建于 2312 天前的主题,其中的信息可能已经有所发展或是发生改变。

    新手刚刚学习,两张表,多对多数据, 一张老师表(字段: 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)
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3486 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:54 · PVG 18:54 · LAX 03:54 · JFK 06:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.