I have two apps Levels, Classes
with Many To Many Relationships, Levels
can have many Classes
, and Classes
can have many Levels
.
I want classes
and levels
use the same table.
How can I do that?
I tried:
levels/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')
Returns (Error)
child_class.ChildClass.levels: (fields.E340) The field’s intermediary table ‘level_class’ clashes with the table name of ‘level.Level.classes’.
level.Level.classes: (fields.E340) The field’s intermediary table ‘level_class’ clashes with the table name of ‘child_class.ChildClass.levels’.
2
Answers
You are getting this error because you have defined two ManyToManyField relationships in two different models (Level and ChildClass), and you are trying to use the same intermediary table ‘level_class’ for both relationships.
In a many-to-many relationship, you should only define the relationship on one side, and the other side can access it via the related_name attribute.
In your case, you can remove the ManyToManyField from the ChildClass model, and only keep it in the Level model.
Try this: