你如何使用相同的数据库在不同的应用程序之间执行 django 查找?

How do you perform a django lookup between different applications using the same database?

我有以下 class(为简洁起见减少了):

from other.app.models import Enclosure

class Server(models.Model):
    enclosure = models.ForeignKey(Enclosure, null=True, blank=True, db_index=True, related_name='server_enclosure')

    def get_enclosure(self):
        get_enclosure = self.enclosure.server_enclosure.get(rack=10)

models.ForeignKey(外壳 <-- 外壳是 class 在单独的应用程序中。

我的问题正在查询中。我怀疑这不是正确的方法,因为 pylint-django 抱怨。在 django 中是否有更好的方法来执行 get()?

我查看了 django 文档,看起来跨越关系的查找信息是针对同一应用程序中的模型量身定制的。对于跨使用同一数据库的不同应用程序的查找,我似乎找不到任何好的参考模式。

Django 将为您处理跨应用程序甚至跨数据库连接。然而,这将取决于应用程序开发人员/DevOps 来确保跨数据库连接实际上是可行的(例如,通过将两个数据库放置在同一个 MySQL 或 PostGRES 实例中)。但是,您拥有的代码看起来比较时髦。要获得 rack=10 的服务器机柜,我将执行以下操作:

from other.app.models import Enclosure

class Server(models.Model):
    enclosure = models.ForeignKey(Enclosure, null=True, blank=True, db_index=True, related_name='server_enclosure')

    @classmethod    
    def get_enclosure(cls):
        return cls.objects.get(rack=10)

要获取与特定服务器相关的附件,您可以使用:

p = Server.objects.get(...)
enclosure = p.enclosure