没有外键的Django中间模型

2024-07-04 07:51:25 发布

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

为我的django应用程序构建一些复杂的模型,并在此获得一些帮助:

Using ManyToMany through correctly for complex model in django

结果到现在为止:

ipaswdb.ProviderLocations: (fields.E336) The model is used as an intermediate model by 'ipaswdb.Group.providers', but it does not have a foreign key to 'Group' or 'Provider'.

我是说是的,错误是英语,但我不知道它到底想告诉我什么。在

下面是完整的模型,但是我们的想法是建立一个拥有多个地点的团队。在

一个提供者通过他们工作的任何一个位置属于一个组,第二个提供者可以在许多位置属于多个组

Provider A -> location 1
         -> location 2
         -> location 3

Group 1 -> has a location 1
        -> has a location 2

Group 2 -> has a location 3
        -> has a location 4

提供者A通过位置1、2、3属于组1和组2

我的全套型号是:

^{pr2}$

我也尝试了编辑ProviderLocations,但没有结果:

class ProviderLocations(models.Model):
    provider = models.ForeignKey('Provider', on_delete=models.CASCADE)
    group = models.ManyToManyField('Group', through='GroupLocations')
    created_at=models.DateField(auto_now_add=True)
    updated_at=models.DateField(auto_now=True)

Tags: django模型automodelmodelsgroup提供者location
1条回答
网友
1楼 · 发布于 2024-07-04 07:51:25

When you set up the intermediary model, you explicitly specify foreign keys to the models that are involved in the many-to-many relationship. This explicit declaration defines how the two models are related

Group(不是GroupLocations)和{}是M2M关系中的两个,因此穿透模型ProviderLocations必须链接到它们的ForeignKeys

class ProviderLocations(models.Model):
    provider = models.ForeignKey('Provider', on_delete=models.CASCADE)
    group = models.ForeignKey('Group', on_delete=models.CASCADE)

同样,每个提供者都有一组组,每个组都有一组组位置,您可以遍历该层次结构来获取对象。在

通过消除ProviderLocations模型并使用GroupLocations作为throughmodel,可以通过组位置使提供者成为组的一部分:

^{pr2}$

相关问题 更多 >

    热门问题