如何创建3路ManyToMany关系django [英] How to create 3 way ManyToMany relationship django
问题描述
需要在django管理员中建立服务器,应用程序和服务器角色之间的关系。
- 服务器可以具有 或许多应用程序
- 应用程序可以托管在一个或许多服务器
- 服务器有一个或多个应用程序角色(DB服务器角色,
WEB服务器角色等)
- $ b $例如:ServerA对于AppX具有角色(Web服务器和Db服务器,2个角色)
- 服务器A对于AppY具有(Web服务器)角色
ServerRole下面的代码是中介模型
这是我在想什么到目前为止,它工作正常,但我缺少某些东西?
类应用程序(models.Model):
name = models .CharField(max_length = 200)
def __unicode __(self):
return self.name
class Server(models.Model):
name = models.CharField(max_length = 200)
apps = models.ManyToMany('Application',related_name ='servers')
class ServerRole(models.Model):
name = models.CharField(max_length = 200)
servers = models.ManyToMany(Server,related_name ='serverrole')
如果我已经明白了你的要求,这更像是你所需要的
code> class ServerRole(models.Model):
name = models.CharField(max_length = 200)
类应用程序(models.Model):
name = models .CharField(max_length = 200)
def __unicode __(self):
return self.name
class Server(models.Model):
name = models.CharField(max_length = 200)
apps = models.ManyToMany('Application',through ='ServerRole',related_name ='servers')
Rational - 服务器可以有很多应用程序,一个应用程序可以有很多服务器。如果一个应用程序在一个特定的服务器上,它应该只有一个角色(如果不是整个系统,因为非常复杂和难以编写),这可以通过多对多关系中的通过模型来实现。 >
Need to model the relationship between servers, applications, and server role, in django admin.
- Server can have one or many applications
- An application can be hosted on one or many servers
- A Server has one or many roles for an app (DB server role,
WEB server role, etc.)
- i.e : ServerA has the role (Web server and Db server, 2 roles) for AppX
- Server A has role of (Web server) for AppY
The code below ServerRole is the intermediary model
Here is what I am thinking. It works fine so far but am I missing something?
class Application(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Server(models.Model):
name = models.CharField(max_length=200)
apps = models.ManyToMany('Application', related_name='servers')
class ServerRole(models.Model):
name = models.CharField(max_length=200)
servers = models.ManyToMany(Server, related_name='serverrole')
If I have understood your requirement correctly, this is more like what you need
class ServerRole(models.Model):
name = models.CharField(max_length=200)
class Application(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Server(models.Model):
name = models.CharField(max_length=200)
apps = models.ManyToMany('Application', through='ServerRole', related_name='servers')
Rational - A server can have many apps and an app can have many servers. if an app is on a particular server it should have only one role on it (if not your whole system because very much more complicated and harder to write) which can be implemented by the through model in a Many to Many relationship.
这篇关于如何创建3路ManyToMany关系django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!