Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What am I doing wrong?

>Solution :

The related_name='marks'. Furthermore you here got the manager, not a queryset, use .all() [Django-doc] to get the objects:

<p>{{ student.marks.all }}</p>

You probably also should enumerate over it, like:

{% for mark in student.marks.all %}
    {{ mark.score }}
{% endfor %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading