在 django 中正确使用 ManyToMany 来处理复杂模型

2024-01-15

我的 django 应用程序中有一个半复杂的模型关系。

我有一个集团(一家企业),可以有很多地点 所以

一个团体也可以有许多提供者(人)。问题是,提供者通过组位置连接到特定组。也就是说,提供商可以拥有该位置。事实上,我相信一个提供商可以有很多位置(属于多个组)。到目前为止,我在 django 中的方式是这样的,我认为这是不正确的:

class GroupLocations(models.Model):
    address_id = models.ForeignKey(Address, on_delete= models.SET_NULL)
    group_id = models.ForeignKey(Group, on_delete=models.SET_NULL)
    doing_business_as = models.CharField(max_length = 255)
    created_at=models.DateField(auto_now=false, auto_now_add=true)
    updated_at=models.DateField(auto_now=true, auto_now_add=true)

class ProviderLocations(models.Model):
    provider_id = models.ForeignKey(Provider, on_delete=models.CASCADE)
    group_location_id = models.ForeignKey(GroupLocations, on_delete=models.CASCADE)
    created_at=models.DateField(auto_now=false, auto_now_add=true)
    updated_at=models.DateField(auto_now=true, auto_now_add=true)

我的问题是,我的组(和/或提供者)模型是否需要在其模型定义中指定某种关系?

class Group(models.Model):
    group_name = models.CharField(max_length=50)
    group_contact= models.CharField(max_length=50)
    #do I need something like the following:
   providers = models.ManyToMany(Provider, through='ProviderLocations')
   provider_locations = models.ManyToMany(Group, through='GroupLocations'


class Provider(models.Model):
    created_at=models.DateField(auto_now=false, auto_now_add=true)
    updated_at=models.DateField(auto_now=true, auto_now_add=true)
    groups = models.ManyToManyField(Group, through='GroupLocations')
    group_locations = models.ManyToMany(GroupLocations, through='ProviderLocations')

这样我就可以从提供商处获取组列表以及组位置 我可以从组中获取提供商列表以及提供商位置。实际上更像是位置加入到哪个位置。我仍在学习 Django 的关系系统,因此任何关于如何使这些关系很好地协同工作的建设性批评都会有所帮助。


我的问题是,我的组(和/或提供商)模型是否需要 他们的模型定义中指定了某种关系?

是的,多对多关系。您只需为一种模型或另一种模型定义它,因为多对多可以在两个方向上遍历。

多对多关系的两端都可以自动获取 API 访问权限 另一端。 API 的工作方式就像“向后”一对多 关系,同上。

唯一的区别在于属性命名:定义的模型 ManyToManyField 使用该字段本身的属性名称, 而“反向”模型使用小写的模型名称 原始模型,加上'_set'(就像反向一对多 关系)。

Source: https://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships https://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships

因此你的模型可以被简化。

class Group(models.Model):
   group_name = models.CharField(max_length=50)
   group_contact= models.CharField(max_length=50)

   providers = models.ManyToMany(Provider, through='ProviderLocations')


class Provider(models.Model):
    created_at=models.DateField(auto_now=false, auto_now_add=true)
    updated_at=models.DateField(auto_now=true, auto_now_add=true)

我不太清楚你为什么要尝试创建两个GroupLocation and ProviderLocation模型。我确实相信它们可以合并。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 django 中正确使用 ManyToMany 来处理复杂模型 的相关文章

随机推荐