select_related和prefetch_related - 未在查询中获得结果

时间:2018-03-01 11:46:17

标签: django django-models django-views django-queryset

我正在尝试制作简单的学习项目,我将获取所有记录并在html上显示。 我的模特是:

class Student(models.Model):
 stuName = models.CharField(max_length=100)
 stuCity = models.CharField(max_length=100)
 stuPhone = models.IntegerField(max_length=10)
 stuNationality = models.CharField(max_length=50)
 stuCreatedt = models.DateTimeField(default=timezone.now)
 def __str__(self):
     return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality)


class Dept(models.Model):
 deptId = models.AutoField(primary_key=True)
 deptName = models.CharField(max_length=100)
 def __str__(self):
      return '%s %s' % (self.deptId, self.deptName)




class Course(models.Model):
 courseId = models.AutoField(primary_key=True)
 courseName = models.CharField(max_length=100)
 enrolledStu = models.IntegerField(max_length=3)
 students = models.ManyToManyField(Student)
 dept = models.ForeignKey(Dept, on_delete=models.CASCADE)
 def __str__(self):
      return '%s %s %s %s' % (self.courseName,self.enrolledStu,self.students,self.dept)

从这个模型我试图使用以下查询显示学生,课程和部门信息:

course = Course.objects.all().prefetch_related('students').select_related('dept')

我的HTML代码是:

{% for c in course %}
    <tr>
        <td>{{c.students.stuName}}</td>
        <td>{{c.students.stuCity}}</td>
        <td>{{c.dept.deptName}}</td>
        <td>{{c.courseName}}</td>
        <td><a href="#">Edit</a> </td>
    </tr>
{% endfor %}

我无法显示学生信息..任何人都可以帮我纠正错误。我假设我的查询不正确。

约旦

2 个答案:

答案 0 :(得分:0)

由于students是多个字段,并且包含学生列表,因此您需要迭代students.all以获取学生信息:

{% for c in course %}
    <tr>
        {% for student in c.students.all %} 
            <td>{{student.stuName}}</td>
            <td>{{student.stuCity}}</td>
        {% endfor %} 
        <td>{{c.dept.deptName}}</td>
        <td>{{c.courseName}}</td>
        <td><a href="#">Edit</a> </td>
    </tr>
{% endfor %}

答案 1 :(得分:0)

对于每门课程,您可以显示有关课程的独特详情,然后在下表中显示已注册的学生...

{% for c in course %}
    <p>{{c.dept.deptName}}</p>
    <p>{{c.courseName}}</p>
    <p><a href="#">Edit</a> </p>

    {% for s in c.students.all %}
    <tr> 
        <td>{{s.stuName}}</td>
        <td>{{s.stuCity}}</td>
    </tr>
    {% endfor %}
{% endfor %}