如何摆脱sqlalchemy.exc.noreferendtableerror?

发布于 2025-01-27 07:42:36 字数 1949 浏览 2 评论 0原文

这是与问题有关的一些代码:

db_session.py

import sqlalchemy as sa
import sqlalchemy.orm as orm
import sqlalchemy.ext.declarative as dec

SqlAlchemyBase = dec.declarative_base()

__Session = None


def create_session():
    global __Session
    global_init()
    return __Session()


def global_init():
    global __Session

    if __Session:
        return

    conn_str = f'sqlite:///sqlite.db'

    engine = sa.create_engine(conn_str, echo=True, future=True)
    __Session = orm.sessionmaker(bind=engine)

    SqlAlchemyBase.metadata.create_all(engine)

来自user.department_id列)

import sqlalchemy
from db_session import SqlAlchemyBase


class User(SqlAlchemyBase):
    __tablename__ = 'users'

    id = sqlalchemy.Column(sqlalchemy.Integer,
                           primary_key=True, autoincrement=True)
    department_id = sqlalchemy.Column(sqlalchemy.Integer, 
                                      sqlalchemy.ForeignKey('departments.id'), nullable=True)

部门。

import sqlalchemy
from db_session import SqlAlchemyBase


class Departments(SqlAlchemyBase):
    __tablename__ = 'departments'

    id = sqlalchemy.Column(sqlalchemy.Integer, 
                           primary_key=True, autoincrement=True)
    chief = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey("users.id"))
    members = sqlalchemy.orm.relationship("User", foreign_keys="User.department_id")

user.py(错误 这是错误文本:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'users.department_id' could not find table 'departments' with which to generate a foreign key to target column 'id'

我已经使用数据库管理软件检查了sqlite.db文件,并且肯定有“部门”表。我已经打印了输出

SqlAlchemyBase.metadata.tables.keys()

,“部门”表也在那里,甚至有正确的名称。我尝试在“部门”桌子上添加一些东西,但这也无济于事。所有表的名称均以 tablename 属性明确设置,因此Sqlalchemy的自动桌命名不是问题。如何摆脱此错误?

Here's some code related to the problem:

db_session.py

import sqlalchemy as sa
import sqlalchemy.orm as orm
import sqlalchemy.ext.declarative as dec

SqlAlchemyBase = dec.declarative_base()

__Session = None


def create_session():
    global __Session
    global_init()
    return __Session()


def global_init():
    global __Session

    if __Session:
        return

    conn_str = f'sqlite:///sqlite.db'

    engine = sa.create_engine(conn_str, echo=True, future=True)
    __Session = orm.sessionmaker(bind=engine)

    SqlAlchemyBase.metadata.create_all(engine)

User.py (error comes from User.department_id column)

import sqlalchemy
from db_session import SqlAlchemyBase


class User(SqlAlchemyBase):
    __tablename__ = 'users'

    id = sqlalchemy.Column(sqlalchemy.Integer,
                           primary_key=True, autoincrement=True)
    department_id = sqlalchemy.Column(sqlalchemy.Integer, 
                                      sqlalchemy.ForeignKey('departments.id'), nullable=True)

Departments.py

import sqlalchemy
from db_session import SqlAlchemyBase


class Departments(SqlAlchemyBase):
    __tablename__ = 'departments'

    id = sqlalchemy.Column(sqlalchemy.Integer, 
                           primary_key=True, autoincrement=True)
    chief = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey("users.id"))
    members = sqlalchemy.orm.relationship("User", foreign_keys="User.department_id")

The error occurs whenever I try to access the 'users' table. Here's the error text:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'users.department_id' could not find table 'departments' with which to generate a foreign key to target column 'id'

I've checked the sqlite.db file with database management software and there definitely is 'departments' table. I've printed the output of

SqlAlchemyBase.metadata.tables.keys()

and the 'departments' table is there, too, and even has the right name. I've tried to add something to the 'departments' table, but that also didn't help. All tables' names are set explicitly with tablename property, so sqlalchemy's automatic table naming isn't the problem. How do I get rid of this error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凡尘雨 2025-02-03 07:42:36

感谢@snakecharmerb的解决方案!

事实证明,我不得不在使用Sqlalchemy用户模型的任何地方导入部门班级以查找所有表。

Thanks to @snakecharmerb for the solution!

Turns out, I had to import the Departments class everywhere I used the Users model for sqlalchemy to find all tables.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文