models.py 对应的配置
class Classes(models.Model):
caption = models.CharField(max_length=32)
class Teacher(models.Model):
name = models.CharField(max_length=32)
cls = models.ManyToManyField('Classes')
修改 views.py
@auth
def handle_teacher(request):
current_user = request.session.get('username')
# teacher_list = models.Teacher.objects.all()
# for obj in teacher_list:
# print(obj.id, obj.name, obj.cls.all())
# 分页,获取第一页5位老师对应的记录
teacher_list = models.Teacher.objects.filter(id__in=models.Teacher.objects.all()[0:5]).values('id', 'name', 'cls__id', 'cls__caption')
result = {}
for t in teacher_list:
# 判断是否已在 result 中
if t['id'] in result:
# 判断 cls__id 的值是否为空
if t['cls__id']:
result[t['id']]['cls_list'].append({'id': t['cls__id'], 'caption': t['cls__caption']})
else:
# cls__id 有值
if t['cls__id']:
temp = [{'id': t['cls__id'], 'caption': t['cls__caption']},]
else:
# cls__id 没值
temp = []
# 给 result 字典添加值
result[t['id']] = {
'nid': t['id'],
'name': t['name'],
'cls_list': temp
}
return render(request, 'teacher.html', {'username': current_user, 'teacher_list': result})
修改 teacher.html
{% extends "layout.html" %}
{% block css %}
.tag{
display: inline-block;
padding: 5px;
border: 1px solid red;
background-color: lightpink;
cursor: pointer;
}
{% endblock %}
{% block content %}
<h1>老师列表</h1>
<table border="1">
<thead></thead>
<tbody>
{% for dic in teacher_list.values %}
<tr>
<td>{{ dic.nid }}</td>
<td>{{ dic.name }}</td>
<td>
{% for c in dic.cls_list %}
<span class="tag" nid="{{ c.id }}">{{ c.caption }}</span>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
{% block js %}
<script>
$(function () {
$('#menu_teacher').addClass('active');
})
</script>
{% endblock %}