[Answered ]-Django: Confusion with accessing database model's foreign key data

1👍

As you mentioned here, you are looking for Student data for currently logged in Parent. Hence you can look for Student data directly from Parent object. Like this:

stud_object = request.user.parent.student

This relation works because Parent has a OneToOne relation with CustomUser (I assume Authentication’s custom User model), hence you should get Parent object from request.user.parent (reverse relation for OneToOne). Also, student field is a ForeignKey of Parent model.

Addionally, I think the relation between Parent and Student should be ManyToMany, because a Student can have multiple parents and one parent can have multiple students (or children).

👤ruddra

0👍

There are two possibilities:

  1. The View code that you have attached should be returning stud_data not None, but I am assuming that you know this and this current state of the code is just for debugging purposes.
  2. The request.user.id contains a value that doesn’t belong to any student’s ID in the database. As you are using filter, it’s not going to complain about it and just return you an empty QuerySet. I’d suggest using the get() filter here which raises the DoesNotExist exception and would help in debugging as well.
def home(request):
    stud_data = Parents.objects.get(student__id = request.user.id)
    return stud_data

Hope it helps!

Best of luck with your new journey!

👤mah

Leave a comment