两个数据库之间的多对多关系 Django

问题描述 投票:0回答:1

我正在构建一个单独的 Django 项目来处理聊天系统,我已经有一个不同的 Django 项目来处理其他所有内容(用户登录信息并提供与聊天无关的 API)。

在这个聊天项目中,它有一个模型

class ChatRoom(models.Model):
    rmid = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=256)
    people = models.ManyToManyField(to=User, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)

还有数据库路由器:

class UserAuthRouter:
    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'auth':
            return 'database_with_django_auth_models'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == 'auth':
            return 'database_with_django_auth_models'
        return None

这允许我使用主项目中相同的用户登录信息,因为我已在设置中连接了数据库。

当我尝试访问

ChatRoom
模型时,我相信因为多对多字段与 Auth lib/模块中的用户模型相关,所以它会导致此错误,因为它被路由到使用其他数据库:

Django.db.utils.ProgrammingError: (1146, 
"Table 'database_with_django_auth_models.apps_chat_chatroom_people' doesn't exist")

但是

apps_chat_chatroom_people
数据表位于包含 ChatRoom 模式的数据库中(即将用于聊天系统的第二个数据库)

处理这个问题的正确方法是什么? 我希望能够使用相同的登录凭据。

django django-models django-authentication django-database
1个回答
0
投票

Django 不支持该功能跨数据库关系

您不能使用来自不同数据库的模型的模型关系,您只能保存一个或多个ID并创建自己的代码以从另一个数据库获取数据。

© www.soinside.com 2019 - 2024. All rights reserved.