Home > Blockchain >  Django: Confusion with accessing database model's foreign key data
Django: Confusion with accessing database model's foreign key data

Time:01-27

This is my first time working with Django and while working I have encountered with a confusion to create a particular statement in views that leads to my desired output. I have created a model 'Parents' which has data of a specific student (Foreign Key), and I am confused to access that student id for further process like working with Attendance, or Results of that specific student. Below are necessary codes and my trial to fetch data.

Models.py

class Students(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    gender = models.CharField(max_length=50)
    address = models.TextField()
    course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING, default=1)
    session_year_id = models.ForeignKey(SessionYearModel, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = models.Manager()

    def __str__(self):
        return self.admin.first_name   " "   self.admin.last_name

class Parents(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    gender = models.CharField(max_length=50)
    **student = models.ForeignKey(Students, on_delete=models.CASCADE)**
    relation = models.CharField(max_length=255)
    address = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = models.Manager()

    def __str__(self):
        return self.admin.first_name   " "   self.admin.last_name

Here I have two models, Students model has all information regarding student and the other model is Parent model which has parent information with its specific student id.

Below is the views file code where I am trying to fetch student id of currently logged in parent,

def HOME(request):
    stud_data = Parents.objects.filter(student__id = request.user.id)
    print(stud_data)
    return None

At the time of page reload, I am able to get an empty QuerySet[] as it is not able to find the id.

Kindly help me finding the solution to this problem, so that I can continue thinking about the development.

Thanks :)

CodePudding user response:

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).

CodePudding user response:

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!

  • Related