2010-11-20 4 views
5

SQLAlchemy bildiren ORM kullanarak bire çok ilişki tanımlamak ve the example çalışmak için çalışırken anlamaya çalışıyorum, ancak bir hata alıyorum benim alt sınıf (daha sonra ilan çünkü ..., doğal olarak) bulunanSQLAlchemy bildirici bire-çok tanımlı değil hata

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.

Ama nasıl hatasız, bunu tanımlamak yapmak edilemez?

kodu: Burada

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:[email protected]: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() 

cevap

13

var ben bunu nasıl:

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