Home > Software design >  How to get queryset of objects in many to many field in Django
How to get queryset of objects in many to many field in Django

Time:03-11

I have two models Student and Classroom in models.py

class Classroom(models.Model):
    classroom_subject = models.CharField(max_length=100)
    classroom_code = models.CharField(max_length= 5, default = '00000')
    teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    student_name = models.CharField(max_length=100)
    classes = models.ManyToManyField(Classroom, blank = True)

I have three tables in my database

student:

user_id student_name
1 4
2 4
3 1

classroom:

id classroom_subject classroom_code
1 maths 12345
2 english 12345
3 biology 12345

student_classes:

id student_id classroom_id
1 4 1
2 4 2
3 1 1

In my views.py

class StudentClassesView(ListView):
    model = Classroom
    template_name = 'student_classroom_list.html'
    context_object_name = 'classroom_list'

    
    def get_queryset(self):
        student_id = self.request.user.id
        return Student.classes.through.objects.filter(
        )

This code returns all the classrooms in student_classes, but i want it to return all the classrooms where the student_id = self.request.user.id

So for example self.request.user.id returns 4, I want all the classrooms in student_classes table where student_id = 4.

CodePudding user response:

Work with:

Classroom.objects.filter(
    student__user=request.user
)

This will retrieve all Classrooms for which a related Student has as user the request.user.

  • Related