ManyToManyField 以及每个字段的不同附加值
ManyToManyField along with different additional value for each
我有以下型号:
class Course(models.Model):
Name = CharField(max_length=32, unique=True,)
class Tutorial(models.Model):
Name = CharField(max_length=64, unique=True,)
Courses = ManyToManyField(Course,)
Index = PosSmallInt()
有很多 Course
,每个 Course
都有 Tutorial
,但是有一些 Course
共享相同的 Tutorial
。
现在,每个 Tutorial
在它所在的 Course
中应该有一个唯一的 Index
。
我想我应该指出 Courses
(ManyToManyField
) 是不久前的常规 Course
(ForeignKey
),这意味着我有重复的 Tutorial
s,我在 Tutorial
的 Meta
class 中有这一行:
unique_together = (('Course', 'Index'))
防止 Course
在同一个 Index
中有不同的 Tutorial
。
但现在它是 ManyToManyField
这是不可能的。
示例:
我有以下 Course
和他们的 Tutorial
:
- C#:
- 语法
- 条件
- 循环
- Python:
- 条件
- 循环
- Lambdas
(为了便于示例,请考虑 "Conditions" 和 "Loops" 具有 完全相同的信息。)
如何在不同的 Course
和不同的 Index
中使用相同的 Tutorial
?
尝试使用 through
属性:
class Tutorial(models.Model):
Name = CharField(max_length=64, unique=True,)
Courses = ManyToManyField(Course, through='TutorialCourse')
class TutorialCourse(models.Model):
tutorial = models.ForeignKey(Tutorial, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
Index = PosSmallInt()
class Meta:
unique_together = (('tutorial', 'course', 'Index'))
我有以下型号:
class Course(models.Model):
Name = CharField(max_length=32, unique=True,)
class Tutorial(models.Model):
Name = CharField(max_length=64, unique=True,)
Courses = ManyToManyField(Course,)
Index = PosSmallInt()
有很多 Course
,每个 Course
都有 Tutorial
,但是有一些 Course
共享相同的 Tutorial
。
现在,每个 Tutorial
在它所在的 Course
中应该有一个唯一的 Index
。
我想我应该指出 Courses
(ManyToManyField
) 是不久前的常规 Course
(ForeignKey
),这意味着我有重复的 Tutorial
s,我在 Tutorial
的 Meta
class 中有这一行:
unique_together = (('Course', 'Index'))
防止 Course
在同一个 Index
中有不同的 Tutorial
。
但现在它是 ManyToManyField
这是不可能的。
示例:
我有以下 Course
和他们的 Tutorial
:
- C#:
- 语法
- 条件
- 循环
- Python:
- 条件
- 循环
- Lambdas
(为了便于示例,请考虑 "Conditions" 和 "Loops" 具有 完全相同的信息。)
如何在不同的 Course
和不同的 Index
中使用相同的 Tutorial
?
尝试使用 through
属性:
class Tutorial(models.Model):
Name = CharField(max_length=64, unique=True,)
Courses = ManyToManyField(Course, through='TutorialCourse')
class TutorialCourse(models.Model):
tutorial = models.ForeignKey(Tutorial, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
Index = PosSmallInt()
class Meta:
unique_together = (('tutorial', 'course', 'Index'))