Dynamic Table Creation and ORM mapping in SqlAlchemy

前端 未结 7 1877
忘了有多久
忘了有多久 2020-12-23 19:18

I\'m fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what

7条回答
  •  余生分开走
    2020-12-23 19:39

    maybe i didn't quite understand what you want, but this recipe create identical column in different __tablename__

    class TBase(object):
        """Base class is a 'mixin'.
        Guidelines for declarative mixins is at:
    
        http://www.sqlalchemy.org/docs/orm/extensions/declarative.html#mixin-classes
    
        """
        id = Column(Integer, primary_key=True)
        data = Column(String(50))
    
        def __repr__(self):
            return "%s(data=%r)" % (
                self.__class__.__name__, self.data
            )
    
    class T1Foo(TBase, Base):
        __tablename__ = 't1'
    
    class T2Foo(TBase, Base):
        __tablename__ = 't2'
    
    engine = create_engine('sqlite:///foo.db', echo=True)
    
    Base.metadata.create_all(engine)
    
    sess = sessionmaker(engine)()
    
    sess.add_all([T1Foo(data='t1'), T1Foo(data='t2'), T2Foo(data='t3'),
             T1Foo(data='t4')])
    
    print sess.query(T1Foo).all()
    print sess.query(T2Foo).all()
    sess.commit()
    

    info in example sqlalchemy

提交回复
热议问题