通过同一个mod建立多个多个关系

2024-09-30 20:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要通过同一个关系表使用ManyToManyField将多个字段从一个模型连接到另一个模型。在

class First(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    foo = models.ManyToManyField(
        'Second',
        related_name='foo',
        through='RelationModel',
        through_fields=('first', 'second')
    )

    bar = models.ManyToManyField(
        'Second',
        related_name='bar',
        through='RelationModel',
        through_fields=('first', 'second')
    )

    baz = models.ManyToManyField(
        'Second',
        related_name='baz',
        through='RelationModel',
        through_fields=('first', 'second')
    )

class RelationModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    status = models.IntegerField(default=0)
    first = models.ForeignKey('First')
    second = models.ForeignKey('Second')

class Second(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

这将导致以下错误:

myapp.First: (models.E003) The model has two many-to-many relations through the intermediate model 'myapp.RelationModel'.

我该如何解决这个问题?为什么不允许这样做?在


Tags: keyiddefaultmodelmodelsclassfirstsecond