Osama Abuhamdan
Osama Abuhamdan

Reputation: 179

Performance of ManyToMany vs ForeignKey with filteration

I am working on a DRF project and I have a question regarding the performance between these two choices:

First: Having a ManyToManyField in the Teacher class. So, to access the students with a Teacher, I will access the 'students' field.

class Student(models.Model):
    ... student data ...


class Teacher(models.Model):
    students = models.ManyToManyField(Student)

Second: I put the teacher as a ForeignKey in the Student class. To check students of a teacher, I will use Student.objects.filter(teacher__id=id)

class Teacher(models.Model):
    ... teacher data ...


class Student(models.Model):
    teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL)

Which is better overall, and especially regarding DB (PostgreSQL). Let's say I have 1M students and 100K teachers.

Note: This is just an example of my real issue. My code is much bigger than this I don't want to start copying everything since my question is just about performance. Let's say that every student can have only one teacher and a teacher can have multiple students.

Best

Upvotes: 0

Views: 222

Answers (1)

Oleksii Tambovtsev
Oleksii Tambovtsev

Reputation: 2834

The two provided options are not equivalent. The first option is the many-to-many relation (every student can have many teachers and every teacher can have many students) while the second option represents the one-to-many relation (every student can have only one teacher).

So, these two data schemes solve different problems.

But if you want to talk about performance, you shouldn't feel much difference on such limits if implemented properly.

Upvotes: 2

Related Questions