I'm trying to figure how to define a one-to-many relationship using SQLAlchemy's declarative ORM, and trying to get the example to work, but I'm getting an error that my sub-class can't be found (naturally, because it's declared later...)
我正在尝试使用SQLAlchemy的声明性ORM来定义如何定义一对多关系,并试图让示例工作,但我收到一个错误,我的子类无法找到(当然,因为它稍后宣布...)
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.
InvalidRequestError:初始化映射器Mapper | Parent | parent时,表达式“Child”无法找到名称(“未定义名称'Child')。如果这是类名,请考虑在定义了两个依赖类之后将此关系()添加到类中。
But how do I define this, without the error?
但是如何定义它,没有错误?
The code:
代码:
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()
1 个解决方案
#1
13
Here's how I do it:
我是这样做的:
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()
#1
13
Here's how I do it:
我是这样做的:
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()