【Flask】ORM 关系一对一
### 一对一的关系:
在sqlalchemy中,如果想要将两个模型映射成一对一的关系,那么应该在父模型中,指定引用的时候,要传递一个`uselist=False`这个参数进去。就是告诉父模型,以后引用这个从模型的时候,不再是一个列表了,而是一个对象了。示例代码如下:
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 # UserExtent 38 class UserExtend(Base): 39 __tablename__ = 'userextend' 40 id = Column(Integer, primary_key=True, autoincrement=True) 41 school = Column(String(50)) 42 uid = Column(Integer, ForeignKey("user.id")) 43 44 user = relationship("User", backref=backref("extend", uselist=False)) 45 46 47 # article 48 class Article(Base): 49 __tablename__ = 'article' 50 id = Column(Integer, primary_key=True, autoincrement=True) 51 title = Column(String(50), nullable=False) 52 conent = Column(Text, nullable=False) 53 uid = Column(Integer, ForeignKey("user.id", ondelete="RESTRICT")) 54 55 # relation 正向引用, backref反向引用 56 author = relationship("User", backref='articles') 57 58 def __repr__(self): 59 return "Article <title: {}>".format(self.title) 60 61 62 Base.metadata.drop_all() 63 Base.metadata.create_all() 64 65 # 一对多 66 user = User(username='saber') 67 # article1 = Article(title='title1', conent='content1') 68 # article2 = Article(title='title2', conent='content2') 69 # user.articles.append(article1) 70 # user.articles.append(article2) 71 # 72 # session.add(user) 73 # session.commit() 74 print '-' * 20 75 76 # 一对一, 多对一 77 extend1 = UserExtend(school='tinghua') 78 user.extend = extend1 79 session.add(user) 80 session.commit()