此代码保存数据并根据需要显示数据。但是在显示课程时,它会显示为,]> 。 QuerySet []。i只希望显示课程名称。我该怎么做
models.py
class Teacher(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=50)
phone = models.CharField(max_length=15)
email = models.EmailField()
image = models.ImageField(upload_to='Teachers',blank=True)
courses = models.ManyToManyField(Course)
views.py
def viewteacher(request):
teachers = Teacher.objects.all().order_by('-joined_date')
year1 = datetime.datetime.today().year
return render(request,'students/view_teacher.html',{'teachers':teachers,'year_list':range(2016,year1+1)})
模板
{% for teacher in teachers %}
<tr>
<td>{{teacher.name}}</div></td>
<td>{{teacher.courses.all}}</td>
<td>{{teacher.address}}</td>
<td>{{teacher.phone}}</td>
<td><a href="{% url 'students:profile_teacher' teacher.id %}">Profile</a></td>
<td><a href="{% url 'students:edit_teacher' teacher.id %}">Edit</a></td>
<td><a href="{% url 'students:confirm_delete_teacher' teacher.id %}">Delete</a></td>
</tr>
{% endfor %}
</tbody>
答案 0 :(得分:1)
QuerySet
的呈现方式类似于<QuerySet [ ... ]>
,因此您可以遍历查询集并正确呈现它,例如:
{% for teacher in teachers %}
<tr>
<td>{{teacher.name}}</div></td>
<td>{% for course in teacher.courses %} {{course.name}} {% endfor %}</td>
<td>{{teacher.address}}</td>
<td>{{teacher.phone}}</td>
<td><a href="{% url 'students:profile_teacher' teacher.id %}">Profile</a></td>
<td><a href="{% url 'students:edit_teacher' teacher.id %}">Edit</a></td>
<td><a href="{% url 'students:confirm_delete_teacher' teacher.id %}">Delete</a></td>
</tr>
{% endfor %}
但是,获取每位老师的课程列表并不是很有效。您可以使用.prefetch_related
来加快此过程。然后它将执行有限数量的查询以获取所有课程,并将其正确链接到正确的教师:
def viewteacher(request):
teachers = Teacher.objects.prefetch_related('courses').order_by('-joined_date')
year1 = datetime.datetime.today().year
return render(
request,
'students/view_teacher.html',
{'teachers':teachers,'year_list':range(2016,year1+1)}
)