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

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?

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

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