多个模型到一个manytomanyfield表



我有两个应用程序Levels, Classes与多对多关系,Levels可以有许多Classes,Classes可以有许多Levels

我想让classeslevels使用同一个表

我该怎么做呢?

我试着:

水平/models.py

class Level(models.Model):
name = models.CharField(max_length=50)
classes = models.ManyToManyField(ChildClass, related_name='childclass', blank=True,db_table='level_class', primary_key=False)

child_class/models.py

class ChildClass(models.Model):
name = models.CharField(max_length=50)
levels = models.ManyToManyField('level.Level', related_name='childclass',db_table='level_class')
<<p>回报em>(错误)

child_class.ChildClass。字段的中间表"level_class"与表名"level.Level.classes"冲突。level.Level.classes:(fields.E340)字段的中间表'level_class'与表名'child_class.ChildClass.levels'冲突

你得到这个错误,因为你已经定义了两个ManyToManyField关系在两个不同的模型(Level和ChildClass),你正试图使用相同的中间表'level_class'为这两个关系。

在多对多关系中,您应该只在一端定义关系,而另一端可以通过related_name属性访问它。

在你的例子中,你可以从ChildClass模型中删除ManyToManyField,只保留它在Level模型中。

试试这个:

#levels/models.py
from django.db import models
from child_class.models import ChildClass
class Level(models.Model):
name = models.CharField(max_length=50)
classes = models.ManyToManyField(ChildClass, related_name='levels', blank=True)
#child_class/models.py
from django.db import models
class ChildClass(models.Model):
name = models.CharField(max_length=50)

According to the Django documentation, https://docs.djangoproject.com/en/4.2/topics/db/models/, under many to many relationship you can create an intermediary model to Foreign key both the Level and Class models to hold the fields that are common and govern both the models. Also the many to many relationship can only be defined on one model not both and it is recommended you put the relationship on a model that brings sense.
class Level(models.Model):
name = models.CharField(max_length=128

class ChildClass(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Level, through="Intermediate")

class Intermediate(models.Model):
Level= models.ForeignKey(Level, on_delete=models.CASCADE)
ChildClass= models.ForeignKey(ChildClass, on_delete=models.CASCADE)

最新更新