python---ORM之SQLAlchemy(3)外键与relationship的关系
relationship是为了简化联合查询join等,创建的两个表之间的虚拟关系,这种关系与标的结构时无关的。他与外键十分相似,确实,他必须在外键的基础上才允许使用
不然会报错:
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Father.son - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression
详细的relationship可以点击这里进行查看
relationship的使用:
使两个表之间产生管理,类似于合成一张表,可以直接取出关联的表,进行获取数据,而不需要join操作
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Column,String,Integer,ForeignKey
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy.ext.declarative import declarative_base engine = create_engine("mysql+pymysql://root:root@127.0.0.1/t1") Base = declarative_base() class Father(Base):
__tablename__ = "father" id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(),unique=True)
age = Column(Integer)
son = relationship('Son',backref="father") class Son(Base):
__tablename__ = 'son' id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(),unique=True)
age = Column(Integer) father_id = Column(Integer,ForeignKey('father.id')) Base.metadata.create_all(engine) MySession = sessionmaker(bind=engine)
session = MySession() # f = Father(name='ld',age=)
# session.add(f)
# session.commit()
#
# s1 = Son(name='ww',age=,father_id=)
# s2 = Son(name='wb',age=,father_id=)
# session.add_all([s1,s2])
# session.commit()
#一对多情况下:多(包含外键方) ret =session.query(Father).filter_by(id=).first()
#ret.son 是一个列表,其中多的一方会获得一个列表结果,列表中含有其各个对象
for i in ret.son:
print(i.name,i.age) #另一方只会获得一个对象结果
ret2 = session.query(Son).filter_by(id=).first()
print(ret2.father.name)#
原来代码,不需要看
只使用外键,需要使用join才可以取出数据
#上面不存在relationship
ret = session.query(Father.name.label('kkk'),Son.name.label("ppp")).join(Son).all()#使用Join才可以获取对方数据
print(ret)#是一个列表,列表中存在所要获取的数据(以元组存在)
在外键基础上使用relationship:可以直接通过属性操作获取数据
#使用了relationship
ret = session.query(Father).filter_by(id=).first()
print(ret.son)#是一个对象列表,其中包含了所有查询数据
全部代码:
其中son = relationship('Son',backref="Father")
相当于在Son中加入father = relationship('Father')在Father中加入son = relationship('Son')
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Column,String,Integer,ForeignKey
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy.ext.declarative import declarative_base engine = create_engine("mysql+pymysql://root:root@127.0.0.1/t1") Base = declarative_base() class Father(Base):
__tablename__ = "father" id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(),unique=True)
age = Column(Integer)
son = relationship('Son',backref="Father")
#son = relationship('Son') class Son(Base):
__tablename__ = 'son' id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(),unique=True)
age = Column(Integer)
#father = relationship('Father') father_id = Column(Integer,ForeignKey('father.id')) Base.metadata.create_all(engine) MySession = sessionmaker(bind=engine)
session = MySession() ret = session.query(Father).filter_by(id=).first()
print(ret.son) #多个结果[<__main__.Son object at 0x0000000003F192B0>, <__main__.Son object at 0x0000000003F19320>]
#需要循环取值 ret = session.query(Son).filter_by(id=).first()
print(ret.father)#一个结果<__main__.Father object at 0x0000000003F196D8>
#直接取值
python---ORM之SQLAlchemy(3)外键与relationship的关系的更多相关文章
- Python自动化之sqlalchemy复合外键
复合外键用法 metadata = MetaData(engine) classedu = Table('classedu', metadata, # Column('qq', BigInteger, ...
- sqlalchemy的外键与relationship查询
https://www.cnblogs.com/goldsunshine/p/9269880.html 讲的很详细. http://www.bjhee.com/flask-ext4.html 思诚之道 ...
- sqlalchemy外键和relationship查询
前面的文章中讲解了外键的基础知识和操作,上一篇文章讲解了sqlalchemy的基本操作.前面两篇文章都是作为铺垫,为下面的文章打好基础.记得初一时第一次期中考试时考的不好,老爸安慰我说:“学习是一个循 ...
- sqlalchemy操作----外键关联,relationship
... #!_*_coding:utf-8_*_ #__author__:"Alex huang" import sqlalchemy from sqlalchemy import ...
- SQLAlchemy(三):外键、连表关系
SQLAlchemy03 /外键.连表关系 目录 SQLAlchemy03 /外键.连表关系 1.外键 2.ORM关系以及一对多 3.一对一的关系 4.多对多的关系 5.ORM层面的删除数据 6.OR ...
- SQLAlchemy03 /外键、连表关系
SQLAlchemy03 /外键.连表关系 目录 SQLAlchemy03 /外键.连表关系 1.外键 2.ORM关系以及一对多 3.一对一的关系 4.多对多的关系 5.ORM层面的删除数据 6.OR ...
- python 外键用法 多对多关系 ORM操作 模板相关
一.app/models中写类(设计表结构) 1.普通类 class A(models.Model): id=modles.AutoField(primary_key=True) name=mode ...
- Python之SQLAlchemy学习--外键约束问题
以下问题赞为解决: # class User(Base):# __tablename__ = 'user'# #表的结构# id = Column(String(20), primary_key=Tr ...
- sqlalchemy多外键关联
一.前言 如果有张表A的多个字段关联另一张表B的一个字段,就如同一个客户表的账单地址和发货地址,同时关联地址表中的id字段. 二.事例 # -*- coding: UTF-8 -*- from sql ...
随机推荐
- SQL 别名
Sql中添加别名有三种方式:
- docker安装后启动出现错误
重启报错: [root@localhost ~]# systemctl restart docker Job for docker.service failed because the control ...
- Consul vs. Zookeeper
https://www.consul.io/intro/vs/zookeeper.html 阿里不用zookeeper而是用consul,京东也在用consul.
- 软件工程_3rd weeks
本周上课的第一件事就是四人组队做工程,因为之前没有太多的准备,所以过程有些仓促,只是最后的结果是好的.有了自己的队伍和课题.感觉就应该这样,平时的我们比较随意,没有一丝的紧迫感,这样会督促着我们完成任 ...
- idea编译器光标变为insert状态
idea鼠标变成inset状态,不能复制.粘贴使用快捷键 1.打开设置 点击 plugins 输入ideavim 把 这个勾去掉!这个是插件的配置问题. 2.如果上面的不管用,那么检查editor- ...
- 函数 for 循环有return 返回是0的原因
- ceph 安装ceph问题汇总
1.在不同节点安装ceph时,出现以下异常: 参考这里 ceph deploy RuntimeError: NoSectionError: No section: 'ceph' 解决方法: 在报错的机 ...
- day12 max min zip 用法
max min ,查看最大值,最小值 基础玩法 l = [1,2,3,4,5] print(max(l)) print(min(l)) 高端玩法 默认字典的取值是key的比较 age_dic={'al ...
- windows 系统无法安装
1. 提示windows 无法安装到这个磁盘,选中的磁盘具有MBR分区表. Windows cannot be installed to this disk.the selected disk has ...
- 自学Linux Shell3.6-文件查看命令file cat more less tail head
点击返回 自学Linux命令行与Shell脚本之路 3.6-文件查看命令file cat more less tail head 1.参看文件类型file 该命令用来识别文件类型,也可用来辨别一些文件 ...