sqlalchemy(二)高级用法

外键以及relationship

首先创建数据库,在这里一个user对应多个address,因此需要在address上增加user_id这个外键(一对多)。

#!/usr/bin/env python
# encoding: utf-8

from sqlalchemy import create_engine
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import ForeignKey
from sqlalchemy.orm import backref
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = ‘users‘

    id = Column(Integer, primary_key=True)
    name = Column(String(32))

    addresses = relationship("Address", order_by="Address.id", backref="user")

class Address(Base):
    __tablename__ = ‘addresses‘
    id = Column(Integer, primary_key=True)
    email_address = Column(String(32), nullable=False)
    user_id = Column(Integer, ForeignKey(‘users.id‘))

    #user = relationship("User", backref=backref(‘addresses‘, order_by=id))

engine  = create_engine(‘mysql://root:[email protected]:3306/test‘, echo=True)
#Base.metadata.create_all(engine) 

接下来,调用user和address来添加数据,

>>> jack = User(name=‘jack‘)
>>> jack.address
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: ‘User‘ object has no attribute ‘address‘
>>> jack.addresses
[]
>>> jack.addresses = [Address(email_address=‘[email protected]‘), Address(email_address=‘[email protected]‘)]
>>> jack.addresses
[<demo.Address object at 0x7f2536564f90>, <demo.Address object at 0x7f2535dc71d0>]
>>> session.add(jack)
>>> session.commit()
2015-08-19 13:45:36,237 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE ‘sql_mode‘
2015-08-19 13:45:36,237 INFO sqlalchemy.engine.base.Engine ()
2015-08-19 13:45:36,238 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2015-08-19 13:45:36,238 INFO sqlalchemy.engine.base.Engine ()
2015-08-19 13:45:36,239 INFO sqlalchemy.engine.base.Engine show collation where `Charset` = ‘utf8‘ and `Collation` = ‘utf8_bin‘
2015-08-19 13:45:36,239 INFO sqlalchemy.engine.base.Engine ()
2015-08-19 13:45:36,239 INFO sqlalchemy.engine.base.Engine SELECT CAST(‘test plain returns‘ AS CHAR(60)) AS anon_1
2015-08-19 13:45:36,239 INFO sqlalchemy.engine.base.Engine ()
2015-08-19 13:45:36,240 INFO sqlalchemy.engine.base.Engine SELECT CAST(‘test unicode returns‘ AS CHAR(60)) AS anon_1
2015-08-19 13:45:36,240 INFO sqlalchemy.engine.base.Engine ()
2015-08-19 13:45:36,240 INFO sqlalchemy.engine.base.Engine SELECT CAST(‘test collated returns‘ AS CHAR CHARACTER SET utf8) COLLATE utf8_bin AS anon_1
2015-08-19 13:45:36,240 INFO sqlalchemy.engine.base.Engine ()
2015-08-19 13:45:36,241 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2015-08-19 13:45:36,242 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name) VALUES (%s)
2015-08-19 13:45:36,242 INFO sqlalchemy.engine.base.Engine (‘jack‘,)
2015-08-19 13:45:36,243 INFO sqlalchemy.engine.base.Engine INSERT INTO addresses (email_address, user_id) VALUES (%s, %s)
2015-08-19 13:45:36,243 INFO sqlalchemy.engine.base.Engine (‘[email protected]‘, 1L)
2015-08-19 13:45:36,243 INFO sqlalchemy.engine.base.Engine INSERT INTO addresses (email_address, user_id) VALUES (%s, %s)
2015-08-19 13:45:36,243 INFO sqlalchemy.engine.base.Engine (‘[email protected]‘, 1L)
2015-08-19 13:45:36,244 INFO sqlalchemy.engine.base.Engine COMMIT
>>> 

此时,查看数据库,可以得到刚才插入的数据,

mysql> select * from users;
+----+------+
| id | name |
+----+------+
|  1 | jack |
+----+------+
1 row in set (0.00 sec)

mysql> select * from addresses;
+----+-----------------+---------+
| id | email_address   | user_id |
+----+-----------------+---------+
|  1 | [email protected]   |       1 |
|  2 | [email protected] |       1 |
+----+-----------------+---------+
2 rows in set (0.00 sec)

join查询

如果不使用join的话,可以直接联表查询,

>>> session.query(User.name, Address.email_address).filter(User.id==Address.user_id).filter(Address.email_address==‘[email protected]‘).all()
2015-08-19 14:02:02,877 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name, addresses.email_address AS addresses_email_address
FROM users, addresses
WHERE users.id = addresses.user_id AND addresses.email_address = %s
2015-08-19 14:02:02,878 INFO sqlalchemy.engine.base.Engine (‘[email protected]‘,)
[(‘jack‘, ‘[email protected]‘)]

在sqlalchemy中提供了Queqy.join()函数,

>>> session.query(User).join(Address).filter(Address.email_address==‘[email protected]‘).first()
2015-08-19 14:06:56,624 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name
FROM users INNER JOIN addresses ON users.id = addresses.user_id
WHERE addresses.email_address = %s
 LIMIT %s
2015-08-19 14:06:56,624 INFO sqlalchemy.engine.base.Engine (‘[email protected]‘, 1)
<demo.User object at 0x7f9a74139a10>
>>> session.query(User).join(Address).filter(Address.email_address==‘[email protected]‘).first().name
2015-08-19 14:07:04,224 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name
FROM users INNER JOIN addresses ON users.id = addresses.user_id
WHERE addresses.email_address = %s
 LIMIT %s
2015-08-19 14:07:04,224 INFO sqlalchemy.engine.base.Engine (‘[email protected]‘, 1)
‘jack‘
>>> session.query(User).join(Address).filter(Address.email_address==‘[email protected]‘).first().addresses
2015-08-19 14:07:06,534 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name
FROM users INNER JOIN addresses ON users.id = addresses.user_id
WHERE addresses.email_address = %s
 LIMIT %s
2015-08-19 14:07:06,534 INFO sqlalchemy.engine.base.Engine (‘[email protected]‘, 1)
2015-08-19 14:07:06,535 INFO sqlalchemy.engine.base.Engine SELECT addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id
FROM addresses
WHERE %s = addresses.user_id ORDER BY addresses.id
2015-08-19 14:07:06,535 INFO sqlalchemy.engine.base.Engine (1L,)
[<demo.Address object at 0x7f9a74139350>, <demo.Address object at 0x7f9a741390d0>]
>>> 

注意,上面的用法的前提是存在外键的情况下,如果没有外键,那么可以使用,

query.join(Address, User.id==Address.user_id)    # explicit condition
query.join(User.addresses)                       # specify relationship from left to right
query.join(Address, User.addresses)              # same, with explicit target
query.join(‘addresses‘)    

表的别名

>>> from sqlalchemy.orm import aliased
>>> adalias1 = aliased(Address)

子查询

假设我们需要这样一个查询,

mysql> SELECT users.*, adr_count.address_count FROM users LEFT OUTER JOIN
    ->     (SELECT user_id, count(*) AS address_count
    ->         FROM addresses GROUP BY user_id) AS adr_count
    ->     ON users.id=adr_count.user_id;
+----+------+---------------+
| id | name | address_count |
+----+------+---------------+
|  1 | jack |             2 |
+----+------+---------------+
1 row in set (0.00 sec)
# 生成子句,等同于(select user_id ... group_by user_id)
>>> sbq = session.query(Address.user_id, func.count(‘*‘).label(‘address_count‘)).group_by(Address.user_id).subquery()

# 联接子句,注意子句中需要使用c来调用字段内容
>>> session.query(User.name, sbq.c.address_count).outerjoin(sbq, User.id==sbq.c.user_id).all()
2015-08-19 14:42:53,425 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name, anon_1.address_count AS anon_1_address_count
FROM users LEFT OUTER JOIN (SELECT addresses.user_id AS user_id, count(%s) AS address_count
FROM addresses GROUP BY addresses.user_id) AS anon_1 ON users.id = anon_1.user_id
2015-08-19 14:42:53,425 INFO sqlalchemy.engine.base.Engine (‘*‘,)
[(‘jack‘, 2L)]
>>>

包含contains

query.filter(User.addresses.contains(someaddress))

数据删除delete

>>> session.delete(jack)
>>> session.query(User).filter_by(name=‘jack‘).count()
0

外键配置

在上面的例子中,删除了user-jack,但是address中的数据并没有删除。

cascade字段用来

addresses = relationship("Address", backref=‘user‘,
    cascade="all, delete, delete-orphan")

原文地址:https://www.cnblogs.com/fengff/p/9285060.html

时间: 2024-10-09 10:48:36

sqlalchemy(二)高级用法的相关文章

redis(二)高级用法

redis(二)高级用法 事务 redis的事务是一组命令的集合.事务同命令一样都是redis的最小执行单元,一个事务中的命令要么执行要么都不执行. 首先需要multi命令来开始事务,用exec命令来执行事务. 127.0.0.1:6379> multi OK 127.0.0.1:6379> hset user:1 name xiaoming QUEUED 127.0.0.1:6379> hset user:1 name daxiong QUEUED 127.0.0.1:6379>

C语言语法笔记 – 高级用法 指针数组 指针的指针 二维数组指针 结构体指针 链表 | IT宅.com

原文:C语言语法笔记 – 高级用法 指针数组 指针的指针 二维数组指针 结构体指针 链表 | IT宅.com C语言语法笔记 – 高级用法 指针数组 指针的指针 二维数组指针 结构体指针 链表 | IT宅.com C语言语法笔记 – 高级用法 指针数组 指针的指针 二维数组指针 结构体指针 链表 本文由 arthinking 发表于315 天前 ⁄ itzhai.com原创文章 ⁄ C语言 ⁄ 评论数 3 ⁄ 被围观 1,775 views+ 指针数组: 在一个数组中,如果它的元素全部都是指针类

Newtonsoft.Json高级用法

手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数据,经过分析一个简单的列表接口每一行数据返回了16个字段,但是手机APP端只用到了其中7个字段,剩余9个字段的数据全部都是多余的,如果接口返回数据为40K大小,也就是说大约20K的数据为无效数据,3G网络下20K下载差不多需要1s,不返回无效数据至少可以节约1s的时间,大大提高用户体验.本篇将为大家

Newtonsoft.Json 高级用法

基本用法 Json.NET是支持序列化和反序列化DataTable,DataSet,Entity Framework和Entity的.下面分别举例说明序列化和反序列化. DataTable: //序列化DataTable DataTable dt = new DataTable(); dt.Columns.Add("Age", Type.GetType("System.Int32")); dt.Columns.Add("Name", Type.G

git log 高级用法

转自:https://github.com/geeeeeeeeek/git-recipes/wiki/5.3-Git-log%E9%AB%98%E7%BA%A7%E7%94%A8%E6%B3%95 内容很详细.实用. 这是一篇在原文(BY atlassian)基础上演绎的译文.除非另行注明,页面上所有内容采用知识共享-署名(CC BY 2.5 AU)协议共享. 每一个版本控制系统的出现都是为了让你记录代码的变化.你可以看到项目的历史记录--谁贡献了什么.bug是什么时候引入的,还可以撤回有问题的

再谈Newtonsoft.Json高级用法

上一篇Newtonsoft.Json高级用法发布以后收到挺多回复的,本篇将分享几点挺有用的知识点和最近项目中用到的一个新点进行说明,做为对上篇文章的补充. 阅读目录 动态改变属性序列化名称 枚举值序列化问题 全局设置 总结 回到顶部 动态改变属性序列化名称 "动态改变属性序列化名称"顾名思义:在不同场景下实体字段序列化后字段名称不同,比如有下面实体A,正常序列化后json为{"Id":"123"} public class A { public

Python 内置函数sorted()有哪些高级用法?

本文和大家分享的主要是python内置函数sorted()的相关内容,一起来看看吧,希望对大家学习python http://www.maiziedu.com/land/python/有所帮助. 1.对于 Python 内置函数 sorted() ,先拿来跟list(列表)中的成员函数 list.sort() 进行下对比.在本质上,list的排序和内建函数sorted的排序是差不多的,连参数都基本上是一样的. 2.主要的区别在于, list.sort() 是对已经存在的列表进行操作,进而可以改变

细说 ASP.NET Cache 及其高级用法

许多做过程序性能优化的人,或者关注过程程序性能的人,应该都使用过各类缓存技术. 而我今天所说的Cache是专指ASP.NET的Cache,我们可以使用HttpRuntime.Cache访问到的那个Cache,而不是其它的缓存技术. 以前我在[我心目中的Asp.net核心对象] 这篇博客中简单地提过它,今天我打算为它写篇专题博客,专门来谈谈它,因为它实在是太重要了.在这篇博客中, 我不仅要介绍它的一些常见用法,还将介绍它的一些高级用法. 在上篇博客[在.net中读写config文件的各种方法] 的

jquery ajax实例教程和一些高级用法

jquery ajax的调用方式:jquery.ajax(url,[settings]),jquery ajax常用参数:红色标记参数几乎每个ajax请求都会用到这几个参数,本文将介绍更多jquery ajax实例,后面会有一些ajax高级用法 query ajax的调用方式:jquery.ajax(url,[settings]),因为实际使用过程中经常配置的并不多,所以这里并没有列出所有参数,甚至部分参数默认值,就是最佳实践,根本没必要去自己定义,除非有特殊需求,如果需要所有参数,可以查看jq