Skip to main content
 首页 » 编程设计

python之通过正确使用 ManyToMany 来处理 django 中的复杂模型

2025年04月02日43java哥

我的 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 的关系系统,因此对如何使这些关系很好地协同工作的任何建设性批评都会有所帮助。

请您参考如下方法:

My question is, does my Group (and/or Provider) model need to have some sort of relationship specified in their model definitions?

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

Both ends of a many-to-many relationship get automatic API access to the other end. The API works just as a “backward” one-to-many relationship, above.

The only difference is in the attribute naming: The model that defines the ManyToManyField uses the attribute name of that field itself, whereas the “reverse” model uses the lowercased model name of the original model, plus '_set' (just like reverse one-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 和 ProviderLocation 模型。我相信它们可以合并。