SQLAlchemy declarative one-to-many not defined error

前端 未结 1 733
遇见更好的自我
遇见更好的自我 2021-02-09 06:14

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-

相关标签:
1条回答
  • 2021-02-09 06:40

    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()
    
    0 讨论(0)
提交回复
热议问题