Many to many but custom "through table"? #1795
Unanswered
DusanKovacevic94
asked this question in
Q&A
Replies: 3 comments 3 replies
-
To use a custom "through table" for many-to-many relationships in Tortoise ORM, you can follow this example that shows a Student-Course relationship with grades: from tortoise import fields, models, Tortoise
class Student(models.Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=100)
email = fields.CharField(max_length=255)
created_at = fields.DatetimeField(auto_now_add=True)
# The key part is setting up the ManyToManyField with a through model
courses = fields.ManyToManyField(
"models.Course", # Target model
through="models.StudentCourse", # Your custom through model
forward_key="course_id", # Foreign key in through model pointing to Course
backward_key="student_id", # Foreign key in through model pointing to Student
related_name="students", # Name to use when accessing from Course model
)
class Course(models.Model):
id = fields.IntField(pk=True)
title = fields.CharField(max_length=200)
description = fields.TextField()
created_at = fields.DatetimeField(auto_now_add=True)
class StudentCourse(models.Model):
id = fields.IntField(pk=True)
# These foreign keys must match the forward_key and backward_key names above
student = fields.ForeignKeyField("models.Student", related_name="student_courses")
course = fields.ForeignKeyField("models.Course", related_name="student_courses")
# Add any additional fields you need in the through table
grade = fields.CharField(max_length=2, null=True)
class Meta:
# Prevents duplicate enrollments
unique_together = (("student", "course"),) So in simpler terms:
|
Beta Was this translation helpful? Give feedback.
0 replies
-
We definitely want to support this in a more convenient way. Here's a related issue. |
Beta Was this translation helpful? Give feedback.
2 replies
-
@henadzit. Maybe I am missing something, but the code I provided works correctly. Maybe we need to document this. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I want use a model to define a custom "through table" for my models, but I couldn't find an example for it, please help.
Beta Was this translation helpful? Give feedback.
All reactions