gpt4 book ai didi

python - SQLAlchemy 声明一对多未定义错误

转载 作者:太空狗 更新时间:2023-10-29 22:10:04 26 4
gpt4 key购买 nike

我正在尝试弄清楚如何使用 SQLAlchemy 的声明性 ORM 定义一对多关系,并尝试获取 the example工作,但我得到一个错误,我的子类无法找到(自然,因为它是稍后声明的......)

InvalidRequestError: When initializing mapper Mapper|Parent|parent, expression 'Child' failed to locate a name ("name 'Child' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.

但是我该如何定义它而不出现错误呢?

代码:

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from dev.historyMeta import VersionedMeta, VersionedListener

global engine, Base, Session
engine = create_engine('mysql+mysqldb://user:pass@localhost:3306/testdb', pool_recycle=3600)
Base = declarative_base(bind=engine, metaclass=VersionedMeta)
Session = sessionmaker(extension=VersionedListener())


class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child", backref="parent")

class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))

Base.metadata.create_all()

最佳答案

这是我的做法:

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship

engine = create_engine('sqlite://', echo=True)
Base = declarative_base(bind=engine)
Session = sessionmaker(bind=engine)


class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)

class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship(Parent, backref='children')

Base.metadata.create_all()

关于python - SQLAlchemy 声明一对多未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4234493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com