SQLAlchemy classes across files

前端 未结 4 1552
渐次进展
渐次进展 2020-12-02 05:55

I\'m trying to figure out how to have SQLAlchemy classes spread across several files, and I can for my life not figure out how to do it. I am pretty new to SQLAlchemy so for

4条回答
  •  时光取名叫无心
    2020-12-02 06:39

    The simplest solution to your problem will be to take Base out of the module that imports A, B and C; Break the cyclic import.

    base.py

    from sqlalchemy.ext.declarative import declarative_base
    Base = declarative_base()
    

    a.py

    from sqlalchemy import *
    from base import Base
    from sqlalchemy.orm import relationship
    
    class A(Base):
        __tablename__ = "A"
        id  = Column(Integer, primary_key=True)
        Bs  = relationship("B", backref="A.id")
        Cs  = relationship("C", backref="A.id")
    

    b.py

    from sqlalchemy import *
    from base import Base
    
    class B(Base):
        __tablename__ = "B"
        id    = Column(Integer, primary_key=True)
        A_id  = Column(Integer, ForeignKey("A.id"))
    

    c.py

    from sqlalchemy import *
    from base import Base
    
    class C(Base):
        __tablename__ = "C"    
        id    = Column(Integer, primary_key=True)
        A_id  = Column(Integer, ForeignKey("A.id"))
    

    main.py

    from sqlalchemy import create_engine
    from sqlalchemy.orm import relationship, backref, sessionmaker
    
    import base
    
    
    import a
    import b
    import c
    
    engine = create_engine("sqlite:///:memory:")
    base.Base.metadata.create_all(engine, checkfirst=True)
    Session = sessionmaker(bind=engine)
    session = Session()
    
    a1 = a.A()
    b1 = b.B()
    b2 = b.B()
    c1 = c.C()
    c2 = c.C()
    
    a1.Bs.append(b1)
    a1.Bs.append(b2)    
    a1.Cs.append(c1)
    a1.Cs.append(c2)    
    session.add(a1)
    session.commit()
    

    Works on my machine:

    $ python main.py ; echo $?
    0
    

提交回复
热议问题