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的关系的更多相关文章

  1. Python自动化之sqlalchemy复合外键

    复合外键用法 metadata = MetaData(engine) classedu = Table('classedu', metadata, # Column('qq', BigInteger, ...

  2. sqlalchemy的外键与relationship查询

    https://www.cnblogs.com/goldsunshine/p/9269880.html 讲的很详细. http://www.bjhee.com/flask-ext4.html 思诚之道 ...

  3. sqlalchemy外键和relationship查询

    前面的文章中讲解了外键的基础知识和操作,上一篇文章讲解了sqlalchemy的基本操作.前面两篇文章都是作为铺垫,为下面的文章打好基础.记得初一时第一次期中考试时考的不好,老爸安慰我说:“学习是一个循 ...

  4. sqlalchemy操作----外键关联,relationship

    ... #!_*_coding:utf-8_*_ #__author__:"Alex huang" import sqlalchemy from sqlalchemy import ...

  5. SQLAlchemy(三):外键、连表关系

    SQLAlchemy03 /外键.连表关系 目录 SQLAlchemy03 /外键.连表关系 1.外键 2.ORM关系以及一对多 3.一对一的关系 4.多对多的关系 5.ORM层面的删除数据 6.OR ...

  6. SQLAlchemy03 /外键、连表关系

    SQLAlchemy03 /外键.连表关系 目录 SQLAlchemy03 /外键.连表关系 1.外键 2.ORM关系以及一对多 3.一对一的关系 4.多对多的关系 5.ORM层面的删除数据 6.OR ...

  7. python 外键用法 多对多关系 ORM操作 模板相关

    一.app/models中写类(设计表结构) 1.普通类 class  A(models.Model): id=modles.AutoField(primary_key=True) name=mode ...

  8. Python之SQLAlchemy学习--外键约束问题

    以下问题赞为解决: # class User(Base):# __tablename__ = 'user'# #表的结构# id = Column(String(20), primary_key=Tr ...

  9. sqlalchemy多外键关联

    一.前言 如果有张表A的多个字段关联另一张表B的一个字段,就如同一个客户表的账单地址和发货地址,同时关联地址表中的id字段. 二.事例 # -*- coding: UTF-8 -*- from sql ...

随机推荐

  1. "留拍"-注册/登录详解

    1. 注册 打开 “留拍” 软件,进入 主页面 ,然后按 注册 按钮: 在注册页面什么内容 都没有写 上去的情况下,按 完成 按钮: 首先把URL封装起来: public class URL { pu ...

  2. ThreadPoolExecutor使用详解

    ThreadPoolExecutor机制  一.概述 1.ThreadPoolExecutor作为java.util.concurrent包对外提供基础实现,以内部线程池的形式对外提供管理任务执行,线 ...

  3. 查询数据SELECT 之单表查询

    一.单表查询的语法与关键字的执行优先级""" # 单表查询# 单标查询完整与法:# select distinct(关键字,代表查询的意思,后面跟)字段1,字段2...( ...

  4. spss入门

    spss下载地址:http://www.ddooo.com/softdown/53379.htm

  5. 《使用swoole》

    第一 在windows系统搭建swoole环境: 首先,安装cygwin:步骤截图如下 其次,使用cygwin安装swoole: 打开cygwin的终端,进入~目录,并将swoole-src上传到~目 ...

  6. input 的 oninput onkeypress onkeydown onchange 事件的区别

    事件执行顺序: <input type="text" id="foo" onkeydown="console.log('down')" ...

  7. bzoj 3289 : Mato的文件管理 (莫队+树状数组)

    题目链接: https://www.lydsy.com/JudgeOnline/problem.php?id=3289 思路: 求区间最小交换的次数将区间变成一个不降序列其实就是求区间逆序对的数量,这 ...

  8. MT【191】阿波罗尼乌斯圆

    已知$f(x)=2\sqrt{(\cos x+\frac{1}{2})^2+\sin^2 x}-\sqrt{\cos^2 x+(\sin x-\frac{1}{2})^2}$,若$m\ge f(x)$ ...

  9. Nginx多进程高并发、低时延、高可靠机制在缓存(redis、memcache)twemproxy代理中的应用

    1. 开发背景 现有开源缓存代理中间件有twemproxy.codis等,其中twemproxy为单进程单线程模型,只支持memcache单机版和redis单机版,都不支持集群版功能. 由于twemp ...

  10. 【CF715E】Complete the Permutations(容斥,第一类斯特林数)

    [CF715E]Complete the Permutations(容斥,第一类斯特林数) 题面 CF 洛谷 给定两个排列\(p,q\),但是其中有些位置未知,用\(0\)表示. 现在让你补全两个排列 ...