Implementing Many to Many
Peewee provides a field for representing many-to-many relationships, much likeDjango does. This feature was added due to many requests from users, but Istrongly advocate against using it, since it conflates the idea of a field witha junction table and hidden joins. It’s just a nasty hack to provide convenientaccessors.
To implement many-to-many correctly with peewee, you will therefore createthe intermediary table yourself and query through it:
- class Student(Model):
- name = CharField()
- class Course(Model):
- name = CharField()
- class StudentCourse(Model):
- student = ForeignKeyField(Student)
- course = ForeignKeyField(Course)
To query, let’s say we want to find students who are enrolled in math class:
- query = (Student
- .select()
- .join(StudentCourse)
- .join(Course)
- .where(Course.name == 'math'))
- for student in query:
- print(student.name)
To query what classes a given student is enrolled in:
- courses = (Course
- .select()
- .join(StudentCourse)
- .join(Student)
- .where(Student.name == 'da vinci'))
- for course in courses:
- print(course.name)
To efficiently iterate over a many-to-many relation, i.e., list all studentsand their respective courses, we will query the through modelStudentCourse
and precompute the Student and Course:
- query = (StudentCourse
- .select(StudentCourse, Student, Course)
- .join(Course)
- .switch(StudentCourse)
- .join(Student)
- .order_by(Student.name))
To print a list of students and their courses you might do the following:
- for student_course in query:
- print(student_course.student.name, '->', student_course.course.name)
Since we selected all fields from Student
and Course
in the _select_clause of the query, these foreign key traversals are “free” and we’ve done thewhole iteration with just 1 query.
ManyToManyField
The ManyToManyField
provides a field-like API over many-to-manyfields. For all but the simplest many-to-many situations, you’re better offusing the standard peewee APIs. But, if your models are very simple and yourquerying needs are not very complex, ManyToManyField
may work.
Modeling students and courses using ManyToManyField
:
- from peewee import *
- db = SqliteDatabase('school.db')
- class BaseModel(Model):
- class Meta:
- database = db
- class Student(BaseModel):
- name = CharField()
- class Course(BaseModel):
- name = CharField()
- students = ManyToManyField(Student, backref='courses')
- StudentCourse = Course.students.get_through_model()
- db.create_tables([
- Student,
- Course,
- StudentCourse])
- # Get all classes that "huey" is enrolled in:
- huey = Student.get(Student.name == 'Huey')
- for course in huey.courses.order_by(Course.name):
- print(course.name)
- # Get all students in "English 101":
- engl_101 = Course.get(Course.name == 'English 101')
- for student in engl_101.students:
- print(student.name)
- # When adding objects to a many-to-many relationship, we can pass
- # in either a single model instance, a list of models, or even a
- # query of models:
- huey.courses.add(Course.select().where(Course.name.contains('English')))
- engl_101.students.add(Student.get(Student.name == 'Mickey'))
- engl_101.students.add([
- Student.get(Student.name == 'Charlie'),
- Student.get(Student.name == 'Zaizee')])
- # The same rules apply for removing items from a many-to-many:
- huey.courses.remove(Course.select().where(Course.name.startswith('CS')))
- engl_101.students.remove(huey)
- # Calling .clear() will remove all associated objects:
- cs_150.students.clear()
Attention
Before many-to-many relationships can be added, the objects beingreferenced will need to be saved first. In order to create relationships inthe many-to-many through table, Peewee needs to know the primary keys ofthe models being referenced.
Warning
It is strongly recommended that you do not attempt to subclass modelscontaining ManyToManyField
instances.
A ManyToManyField
, despite its name, is not a field in theusual sense. Instead of being a column on a table, the many-to-many fieldcovers the fact that behind-the-scenes there’s actually a separate tablewith two foreign-key pointers (the through table).
Therefore, when a subclass is created that inherits a many-to-many field,what actually needs to be inherited is the through table. Because of thepotential for subtle bugs, Peewee does not attempt to automaticallysubclass the through model and modify its foreign-key pointers. As aresult, many-to-many fields typically will not work with inheritance.
For more examples, see: