django prefetch_related() 属性错误

django prefetch_related() attribute error

如何使用 ManyToMany 关系

正确地使用 prefetch_related

我的模特:

class Subject(models.Model):
    subject_name = models.CharField(max_length=150)
    subject_code = models.CharField(max_length=50)
    year = models.ForeignKey(YearLevel, null=True, on_delete=models.SET_NULL)
    units = models.CharField(max_length=10)

    def __str__(self):
        return self.subject_name + ' ' + '(' + self.subject_code + ')'

class Student(models.Model):
    student = models.ForeignKey(settings.AUTH_USER_MODEL, limit_choices_to= Q(is_student=True), on_delete= models.CASCADE)
    enrolled_subject = models.ManyToManyField(Subject)

我的看法:

def home(request):
    verses = VerseOfTheDay.objects.all()
    news = Announcement.objects.all()
    student_grade_form = AddStudentGradeForm()
    students = Student.objects.all().prefetch_related('subject_set')
    context = {
        "verse": verses,
        'news': news,
        'form': student_grade_form,
        'students': students,

    }
    return render(request, 'sample.html', context)

我的html:

    {% for student in students %}
    <p>
      <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapse{{forloop.counter}}" role="button" aria-expanded="false" aria-controls="collapse{{forloop.counter}}">
        {{student.student}}
      </a>

    </p>
    <div class="collapse" id="collapse{{forloop.counter}}">
      <div class="card card-body">
        {% for subject in student.subject_set.all %}
        {{subject.subject}}
        {% endfor %}
      </div>
    </div>
    {% endfor %}

我收到一个错误:

AttributeError at /
Cannot find 'subject_set' on Student object, 'subject_set' is an invalid parameter to prefetch_related()

更改此行

students = Student.objects.all().prefetch_related('subject_set')

students = Student.objects.all().prefetch_related('enrolled_subject')