Last active
August 29, 2015 13:57
-
-
Save menghan/9461012 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # coding=utf-8 | |
| from sqlalchemy import create_engine, Column, Integer, DECIMAL, DATE, String, ForeignKey, Float, TEXT | |
| from sqlalchemy.ext.declarative import declarative_base | |
| from sqlalchemy.orm import sessionmaker, relationship, backref | |
| db_schema = 'sqlite:///sqlite.db' | |
| debug = True | |
| engine = create_engine(db_schema, echo=debug) | |
| create_session = sessionmaker(bind=engine) | |
| Base = declarative_base() | |
| class M(Base): | |
| __tablename__ = 'm' | |
| id = Column(Integer, primary_key=True) | |
| description_id = Column(Integer, ForeignKey('description.id')) | |
| description = relationship("Description", backref='ms') | |
| class Description(Base): | |
| __tablename__ = 'description' | |
| id = Column(Integer, primary_key=True) | |
| name = Column(String(100)) | |
| def create_m(session, desc): | |
| return M(description_id=add_description(session, desc).id) | |
| def add_description(session, description): | |
| return insert_into_db(session, Description(name=description)) | |
| def insert_into_db(session, ins): | |
| session.add(ins) | |
| session.flush() | |
| return ins | |
| if __name__ == '__main__': | |
| Base.metadata.create_all(engine) | |
| session = create_session() | |
| m = create_m(session, 'desc') | |
| print m.description_id # has value | |
| print m.description # get None | |
| session.commit() | |
| print m.description_id # has value | |
| print m.description # get None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment