python 多个模型到一个多到任意字段表

42fyovps  于 2023-04-10  发布在  Python
关注(0)|答案(2)|浏览(120)

我有两个应用程序Levels, Classes与多对多关系,Levels可以有许多ClassesClasses可以有许多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')

返回 (错误)

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

rfbsl7qr

rfbsl7qr1#

出现此错误的原因是,您在两个不同的模型(Level和ChildClass)中定义了两个ManyToManyField关系,并且试图对这两个关系使用相同的中介表“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)
eufgjt7s

eufgjt7s2#

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)

相关问题