how to filter foreign key

Hello their i have two table one is StudentData and other is Enrollment. Below are the codes for them

class StudentData(models.Model):
    user                = models.OneToOneField(CustomUser,on_delete=models.CASCADE)
    student_name        = models.CharField(max_length=30, default=1)
    department          = models.ForeignKey(Department,on_delete=models.CASCADE)
    program             = models.ForeignKey(Program, on_delete=models.CASCADE)

    is_admitted         = models.BooleanField(default=True)
    is_closed         = models.BooleanField(default=False)
class Enrollment(models.Model):
    student = models.ForeignKey(StudentData,on_delete=models.CASCADE)
    faculty = models.ForeignKey(TeachingSemester,on_delete=models.CASCADE)

When student logins , the website shows data according to logged user , below is the code

log_user = request.user
student_information = StudentData.objects.filter(user=log_user)

What can i do so that the Enrollment of only logged in is shown on the page?

>Solution :

To filter by student:

log_user = request.user
student_information = StudentData.objects.filter(user=log_user)

enrollments = Enrollment.objects.filter(student=student_information)

If you prefer to get Enrollments by user you can also do:

log_user = request.user
enrollments = Enrollment.objects.filter(student__user=log_user)

Leave a Reply