Search code examples
djangodjango-modelsdjango-views

Django reverse ForeignKey returns None


I have Student and Mark models in different apps of one project.

# project/study
# models.py
class Mark(models.Model):
    ...
    student = models.ForeignKey(
        "students.Student",
        on_delete=models.PROTECT,
        related_name="marks",
        related_query_name="mark",
    )


# project/students
# models.py
class Student(models.Model):
    ...

# views.py
class StudentDetailView(DetailView):
    queryset = Student.objects.prefetch_related("marks")
    template_name = "students/one_student.html"
    context_object_name = "student"


# one_student.html
...
    <p>{{ student.marks }}</p>
...

Output of html is "study.Mark.None" That is my problem.

I tried making ManyToOneRel field on student, select_related, making custom view func, but that does not help. Reverse ForeignKey brings None. I watched related questions - can't understand answers, because they are unrelated directly to my situation.

I'm expecting to get all Student's marks.

What am I doing wrong?


Solution

  • We can use django model Prefetch like this:

    from django.db.models import Prefetch
    queryset = Student.objects.prefetch_related(Prefetch("marks", queryset=Mark.objects.all(), to_attr="student_marks"))
    

    In html template you have to iterate over the loop like this:

    {% for mark in student.student_marks %}
        <p>{{ mark }}</p>
    {% endfor %}