### ORM關係以及一對多:
mysql級別的外鍵,還不夠ORM,必須拿到一個表的外鍵,而後經過這個外鍵再去另一張表中查找,這樣太麻煩了。SQLAlchemy提供了一個`relationship`,這個類能夠定義屬性,之後在訪問相關聯的表的時候就直接能夠經過屬性訪問的方式就能夠訪問獲得了。示例代碼:
mysql
1 # coding:utf-8 2 # Author: liangjun.chen 3 4 5 from sqlalchemy import create_engine, Column, Integer, String, Text, ForeignKey 6 7 from sqlalchemy.ext.declarative import declarative_base 8 from sqlalchemy.orm import sessionmaker, relationship, backref 9 10 HOSTNAME = '127.0.0.1' 11 PORT = 3306 12 DATABASE = 'sqlalchemy_first' 13 USERNAME = 'root' 14 PASSWORD = '123456' 15 16 DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{dbname}?charset=utf8'.format( 17 username=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, dbname=DATABASE 18 ) 19 engine = create_engine(DB_URI) 20 Base = declarative_base(engine) 21 Session = sessionmaker(engine) 22 session = Session() 23 24 25 # user 26 class User(Base): 27 __tablename__ = 'user' 28 id = Column(Integer, primary_key=True, autoincrement=True) 29 username = Column(String(50), nullable=False) 30 31 # articles = relationship("Article") 32 33 def __repr__(self): 34 return "User <username: {}>".format(self.username) 35 36 37 # article 38 class Article(Base): 39 __tablename__ = 'article' 40 id = Column(Integer, primary_key=True,autoincrement=True) 41 title = Column(String(50), nullable=False) 42 conent = Column(Text, nullable=False) 43 uid = Column(Integer, ForeignKey("user.id", ondelete="RESTRICT")) 44 45 # relation 正向引用, backref反向引用 46 author = relationship("User", backref='articles') 47 48 def __repr__(self): 49 return "Article <title: {}>".format(self.title) 50 # Base.metadata.drop_all() 51 # Base.metadata.create_all() 52 # 53 # user = User(username='saber') 54 # session.add(user) 55 # session.commit() 56 # 57 # article = Article(title='abd', conent='123', uid=1) 58 # session.add(article) 59 # session.commit() 60 61 article = session.query(Article).first() 62 uid = article.uid 63 user = session.query(User).get(uid) 64 print article 65 print uid 66 print user 67 68 print "-"*20 69 article = session.query(Article).first() 70 print article.author.username 71 72 print '-'*20 73 user = session.query(User).first() 74 print user.articles