SQLAlchemy声明性一对多未定义错误

时间:2010-11-20 19:19:36

标签: python database sqlalchemy

我正在尝试使用SQLAlchemy的声明性ORM来定义如何定义一对多关系,并尝试让the example起作用,但我收到的错误是我的子类可以'找到(当然,因为它后来宣布......)

  

InvalidRequestError:初始化mapper Mapper | Parent | parent时,表达式'Child'找不到名称(“name'未定义'Child')。如果这是一个类名,请考虑在定义了两个依赖类之后将此关系()添加到类中。

但是如何在没有错误的情况下定义它?

代码:

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 个答案:

答案 0 :(得分:14)

我是这样做的:

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()