如何创建 3 路多对多关系 django [英] How to create 3 way ManyToMany relationship django

查看:37
本文介绍了如何创建 3 路多对多关系 django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要在 django admin 中建模服务器、应用程序和服务器角色之间的关系.

Need to model the relationship between servers, applications, and server role, in django admin.

  • 服务器可以有一个许多应用程序
  • 一个应用程序可以托管在一个许多服务器上
  • 服务器为应用提供一个或多个角色(数据库服务器角色、WEB服务器角色等)
    • 即:ServerA 具有 AppX 的角色(Web 服务器和 Db 服务器,2 个角色)
    • 服务器 A 具有 AppY 的(Web 服务器)角色

    ServerRole下面的代码是中介模型

    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 - 一个服务器可以有很多应用程序,一个应用程序可以有很多服务器.如果一个应用在特定的服务器上,它应该只有一个角色(如果不是你的整个系统,因为非常复杂和难以编写),可以通过多对多关系中的直通模型实现.

    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 路多对多关系 django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆