sqlalchemy一对一关系映射
Posted python成长中
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlalchemy一对一关系映射相关的知识,希望对你有一定的参考价值。
#encoding: utf-8 from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,Text, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker,relationship,backref from random import randint HOSTNAME = ‘127.0.0.1‘ PORT = 3306 DATABASE = ‘first_sqlalchemy‘ USERNAME = ‘root‘ PASSWORD = ‘123456‘ #dialect+driver://username:[email protected]:port/database DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base = declarative_base(engine) # Session = sessionmaker(engine) # session = Session() session = sessionmaker(engine)() #Session(**local_kw) #父表/从表 #user/article class User(Base): __tablename__ = ‘user‘ id = Column(Integer,primary_key=True,autoincrement=True) username = Column(String(32),nullable=False) # 一对一的情况,这里要设置下,uselist设置成false,关闭列表让一对多,变成一对一的关系 # extend = relationship(‘UserExtend‘,uselist=False) # articles = relationship("Article") #获取用户发布所有文章 #把不常用到的数据,放到另一张表里,这里就用到一对一 class UserExtend(Base): __tablename__ = ‘user_extend‘ id = Column(Integer, primary_key=True, autoincrement=True) school = Column(String(50)) uid = Column(Integer,ForeignKey(‘user.id‘)) #一对一的时候使用下面情况: user = relationship(‘User‘,backref=backref(‘extend‘,uselist=False)) class Article(Base): __tablename__ = ‘article‘ id = Column(Integer,primary_key=True,autoincrement=True) title = Column(String(50),nullable=False) content = Column(Text,nullable=False) uid = Column(Integer,ForeignKey(‘user.id‘,ondelete=‘RESTRICT‘)) author = relationship(‘User‘,backref=‘articles‘) #sqlalchemy orm提供的 Base.metadata.drop_all() Base.metadata.create_all() user = User(username=‘辰东‘) article1 = Article(title = ‘圣墟‘,content=‘这都是些啥‘) article2 = Article(title = ‘遮天‘,content=‘这又是啥‘) # user.articles 是什么数据类型 print(user.articles,type(user.articles)) #sqlalchemy.orm.collections.InstrumentedList from sqlalchemy.orm.collections import InstrumentedList #InstrumentedList是 ‘‘‘ class InstrumentedList(list): """An instrumented version of the built-in list.""" ‘‘‘ # user.articles.append(article1) # user.articles.append(article2) # # session.add(user) # session.commit() #怎么反向添加呢 # article1.author = user #通过子表的关联字段反向的绑定主表的主键(这个是比较常见的) # # article2.author = user # # session.add(article1) # session.add(article2) # # session.commit() #这里尝试一下一对一的关系 user = User(username=‘xiaowu‘) extend_user = UserExtend(school=‘大渡口中学‘) # extend_user_1 = UserExtend(school=‘大同中学‘) user.extend = extend_user # extend.append(extend_user_1) session.add(user) session.commit()
以上是关于sqlalchemy一对一关系映射的主要内容,如果未能解决你的问题,请参考以下文章
SQLAlchemy - 将自引用关系映射为一对多(声明形式)