initialization
# 检查是否已经安装以及版本号
>>> import sqlalchemy
>>> sqlalchemy.__version__
’1.1.4‘>>> from sqlalchemy.ext.declarative import declarative_base
# model都是要继承自base
>>> base = declarative_base()
>>> from sqlalchemy import column, integer, string
>>> class user(base):
… __tablename__ = ‘users’ # 指定数据表名
…
… id = column(integer, primary_key=true)
… name = column(string(50))
… fullname = column(string(50))
… password = column(string(50))
…
… def __repr__(self):
… return “” % (
… self.name, self.fullname, self.password)
# 查看创建的数据表结构
>>> user.__table__
table(‘users’, metadata(bind=none),
column(‘id’, integer(), table=, primary_key=true, nullable=false),
column(‘name’, string(length=50), table=),
column(‘fullname’, string(length=50), table=),
column(‘password’, string(length=50), table=), schema=none)
正式创建数据表
>>> from sqlalchemy import create_engine
# 连接到mysql
>>> engine = create_engine(“mysql://root:root@localhost:3306/python?charset=utf8″,
encoding=”utf-8”, echo=true)
# 正式创建数据表
>>> base.metadata.create_all(engine)
create table users (
id integer not null auto_increment,
name varchar(50),
fullname varchar(50),
password varchar(50),
primary key (id)
)creating a session
下面的操作都是要通过会话对象操作
>>> from sqlalchemy.orm import sessionmaker
>>> session = sessionmaker(bind=engine)
>>> session = session()adding and updating objects
添加一个user对象
>>> ed_user = user(name=’ed’, fullname=’ed jones’, password=’edspassword’)
>>> session.add(ed_user)
查询一下,使用filter_by来过滤,first只列出第一个查询到的对象
>>> our_user = session.query(user).filter_by(name=’ed’).first()
begin (implicit)
insert into users (name, fullname, password) values (?, ?, ?)
(‘ed’, ‘ed jones’, ‘edspassword’)
select users.id as users_id,
users.name as users_name,
users.fullname as users_fullname,
users.password as users_password
from users
where users.name = ?
limit ? offset ?
(‘ed’, 1, 0)
>>> our_user
>>> ed_user is our_user
true
使用add_all,一次性添加多个对象
>>> session.add_all([
… user(name=’wendy’, fullname=’wendy williams’, password=’foobar’),
… user(name=’mary’, fullname=’mary contrary’, password=’xxg527′),
… user(name=’fred’, fullname=’fred flinstone’, password=’blah’)])
session很智能,比如说,它知道ed jones被修改了
# 可以直接修改ed_user对象
>>> ed_user.password = ‘f8s7ccs’
# session会自动知道哪些数据被修改了
>>> session.dirty
identityset([])
# session也可以知道哪些对象被新建了
>>> session.new
identityset([,
,
])
对数据库进行了变更,自然要进行commit,从echo语句我们可以看出,我们更新了1个对象,创建了3个对象。
>>> session.commit()
update users set password=? where users.id = ?
(‘f8s7ccs’, 1)
insert into users (name, fullname, password) values (?, ?, ?)
(‘wendy’, ‘wendy williams’, ‘foobar’)
insert into users (name, fullname, password) values (?, ?, ?)
(‘mary’, ‘mary contrary’, ‘xxg527’)
insert into users (name, fullname, password) values (?, ?, ?)
(‘fred’, ‘fred flinstone’, ‘blah’)
commit
>>> ed_user.id
begin (implicit)
select users.id as users_id,
users.name as users_name,
users.fullname as users_fullname,
users.password as users_password
from users
where users.id = ?
(1,)
1rolling back
因为session是工作在一个transaction内部,有时候我们可能不小心做了一些误删除的操作,可以回滚。我们先修改ed_user的用户名为edwardo,然后重新添加一个新user,但是记住这个时候我们还没有commit。
>>> ed_user.name = ‘edwardo’
and we’ll add another erroneous user, fake_user:
>>> fake_user = user(name=’fakeuser’, fullname=’invalid’, password=’12345′)
>>> session.add(fake_user)
querying the session, we can see that they’re flushed into the current transaction:
查询检验一下
>>> session.query(user).filter(user.name.in_([‘edwardo’, ‘fakeuser’])).all()
update users set name=? where users.id = ?
(‘edwardo’, 1)
insert into users (name, fullname, password) values (?, ?, ?)
(‘fakeuser’, ‘invalid’, ‘12345’)
select users.id as users_id,
users.name as users_name,
users.fullname as users_fullname,
users.password as users_password
from users
where users.name in (?, ?)
(‘edwardo’, ‘fakeuser’)
[, ]
回滚,我们可以知道ed_user‘s name is back to ed以及fake_user has been kicked out of the session
>>> session.rollback()
rollback
>>> ed_user.name
begin (implicit)
select users.id as users_id,
users.name as users_name,
users.fullname as users_fullname,
users.password as users_password
from users
where users.id = ?
(1,)
u’ed’
>>> fake_user in session
false
issuing a select illustrates the changes made to the database:
这个时候再查询,很明显fakeuser已经消失了,ed用户的名字重新变回了ed而不是edwordo
>>> session.query(user).filter(user.name.in_([‘ed’, ‘fakeuser’])).all()
select users.id as users_id,
users.name as users_name,
users.fullname as users_fullname,
users.password as users_password
from users
where users.name in (?, ?)
(‘ed’, ‘fakeuser’)
[]couting
用于查询操作相对应的count()操作
>>> session.query(user).filter(user.name.like(‘%ed’)).count()
2
>>> from sqlalchemy import func
>>> session.query(func.count(user.name), user.name).group_by(user.name).all()
[(1, u’ed’), (1, u’fred’), (1, u’mary’), (1, u’wendy’)]querying
一个通过在session上使用query方法可以创建一个query object
按照用户id进行排序来进行查询
>>> for instance in session.query(user).order_by(user.id):
… print(instance.name, instance.fullname)
ed ed jones
wendy wendy williams
mary mary contrary
fred fred flinstone
query方法也可以接收orm-instrumented descriptors作为参数。返回结果是一个named tuples
>>> for name, fullname in session.query(user.name, user.fullname):
… print(name, fullname)
ed ed jones
wendy wendy williams
mary mary contrary
fred fred flinstone
the tuples returned by query are named tuples, supplied by the keyedtuple class, and can be treated much like an ordinary python object. the names are the same as the attribute’s name for an attribute, and the class name for a class:
>>> for row in session.query(user, user.name).all():
… print(row.user, row.name)
ed
wendy
mary
fred
you can control the names of inpidual column expressions using the label() construct, which is available from any columnelement-derived object, as well as any class attribute which is mapped to one (such as user.name):
>>> for row in session.query(user.name.label(‘name_label’)).all():
… print(row.name_label)
ed
wendy
mary
fred
the name given to a full entity such as user, assuming that multiple entities are present in the call to query(), can be controlled using aliased() :
>>> from sqlalchemy.orm import aliased
>>> user_alias = aliased(user, name=’user_alias’)
>>> for row in session.query(user_alias, user_alias.name).all():
… print(row.user_alias)
basic operations with query include issuing limit and offset, most conveniently using python array slices and typically in conjunction with order by:
>>> for u in session.query(user).order_by(user.id)[1:3]:
… print(u)
and filtering results, which is accomplished either with filter_by(), which uses keyword arguments:
>>> for name, in session.query(user.name).\
… filter_by(fullname=’ed jones’):
… print(name)
ed
>>> for name, in session.query(user.name).\
… filter(user.fullname==’ed jones’):
… print(name)
ed
the query object is fully generative, meaning that most method calls return a new query object upon which further criteria may be added. for example, to query for users named “ed” with a full name of “ed jones”, you can call filter() twice, which joins criteria using and:
>>> for user in session.query(user).\
… filter(user.name==’ed’).\
… filter(user.fullname==’ed jones’):
… print(user)
common filter operators
下面列出了filter()最常用的一些operators
equals:
query.filter(user.name == ‘ed’)
not equals:
query.filter(user.name != ‘ed’)
like:
query.filter(user.name.like(‘%ed%’))
in:
query.filter(user.name.in_([‘ed’, ‘wendy’, ‘jack’]))
# works with query objects too:
query.filter(user.name.in_(
session.query(user.name).filter(user.name.like(‘%ed%’))
))
not in:
query.filter(user.name.in_([‘ed’, ‘wendy’, ‘jack’]))
is null:
query.filter(user.name == none)
# alternatively, if pep8/linters are a concern
query.filter(user.name.is_(none))
is not null:
query.filter(user.name != none)
# alternatively, if pep8/linters are a concern
query.filter(user.name.isnot(none))
and:
# use and_()
from sqlalchemy import and_
query.filter(and_(user.name == ‘ed’, user.fullname == ‘ed jones’))
# or send multiple expressions to .filter()
query.filter(user.name == ‘ed’, user.fullname == ‘ed jones’)
# or chain multiple filter()/filter_by() calls
query.filter(user.name == ‘ed’).filter(user.fullname == ‘ed jones’)
note
make sure you use and_() and not the python and operator!
or:
from sqlalchemy import or_
query.filter(or_(user.name == ‘ed’, user.name == ‘wendy’))
note
make sure you use or_() and not the python or operator!
match:
query.filter(user.name.match(‘wendy’))
note
match() uses a database-specific match or contains function;
its behavior will vary by backend and is not available on some backends such as sqlite.building a relationship
创建对象与对象之间的关系,下面我们新建一个address表,下面的操作相比django的orm繁琐一些,要同时在两个class内部同时设置relationship
>>> from sqlalchemy import foreignkey
>>> from sqlalchemy.orm import relationship
>>> class address(base):
… __tablename__ = ‘addresses’
… id = column(integer, primary_key=true)
… email_address = column(string(50), nullable=false)
… user_id = column(integer, foreignkey(‘users.id’))
…
… user = relationship(“user”, back_populates=”addresses”) # 将地址表和用户表关联
…
… def __repr__(self):
… return “” % self.email_address
# 在用户表中还要重新设置一次
>>> user.addresses = relationship(
… “address”, order_by=address.id, back_populates=”user”)
>>> base.metadata.create_all(engine)working with related objects
现在我们创建了一个user,与它对应的一个空addresses集合也将创立。集合类型可以是各种合法类型,比如set/dictionaries(see customizing collection access for details),但是默认集合是一个list。
现在我们再来创建一个用户jack
>>> jack = user(name=’jack’, fullname=’jack bean’, password=’gjffdd’)
>>> jack.addresses
[]
we are free to add address objects on our user object. in this case we just assign a full list directly:
现在我们将用户jack和一些地址关联起来
>>> jack.addresses = [
… address(email_address=’jack@google.com’),
… address(email_address=’j25@yahoo.com’)]
when using a bidirectional relationship, elements added in one direction automatically become visible in the other direction. this behavior occurs based on attribute on-change events and is evaluated in python, without using any sql:现在可以通过地址对象访问用户对象了
>>> jack.addresses[1]
>>> jack.addresses[1].user
let’s add and commit jack bean to the database. jack as well as the two address members in the corresponding addresses collection are both added to the session at once, using a process known as cascading:
接下来commit保存到数据库
>>> session.add(jack)
>>> session.commit()
sqlalchemy.engine.base.engine insert into addresses (email_address, user_id) values (%s, %s)
sqlalchemy.engine.base.engine (‘jack@google.com’, 5l)
sqlalchemy.engine.base.engine insert into addresses (email_address, user_id) values (%s, %s)
sqlalchemy.engine.base.engine (‘j25@yahoo.com’, 5l)
sqlalchemy.engine.base.engine commit
querying for jack, we get just jack back. no sql is yet issued for jack’s addresses:
>>> jack = session.query(user).\
… filter_by(name=’jack’).one()
>>> jack
let’s look at the addresses collection. watch the sql:
>>> jack.addresses
[, ]
when we accessed the addresses collection, sql was suddenly issued. this is an example of a lazy loading relationship. the addresses collection is now loaded and behaves just like an ordinary list. we’ll cover ways to optimize the loading of this collection in a bit.
delete
删除操作,接下来我们尝试删除jack对象,注意地址对象并不会因此而删除
>>> session.delete(jack)
>>> session.query(user).filter_by(name=’jack’).count()
0
so far, so good. how about jack’s address objects ?
>>> session.query(address).filter(
… address.email_address.in_([‘jack@google.com’, ‘j25@yahoo.com’])
… ).count()
2
uh oh, they’re still there ! analyzing the flush sql, we can see that the user_id column of each address was set to null, but the rows weren’t deleted. sqlalchemy doesn’t assume that deletes cascade, you have to tell it to do so. configuring delete/delete-orphan cascade. we will configure cascade options on the user.addresses relationship to change the behavior. while sqlalchemy allows you to add new attributes and relationships to mappings at any point in time, in this case the existing relationship needs to be removed, so we need to tear down the mappings completely and start again – we’ll close the session:
直接close来rollback,并不进行commit
>>> session.close()
rollback
use a new declarative_base():
>>> base = declarative_base()
next we’ll declare the user class, adding in the addresses relationshipincluding the cascade configuration (we’ll leave the constructor out too):
>>> class user(base):
… __tablename__ = ‘users’
…
… id = column(integer, primary_key=true)
… name = column(string(50))
… fullname = column(string(50))
… password = column(string(50))
…
… addresses = relationship(“address”, back_populates=’user’,
… cascade=”all, delete, delete-orphan”)
…
… def __repr__(self):
… return “” % (
… self.name, self.fullname, self.password)
then we recreate address, noting that in this casewe’ve created the address.user relationship via the user class already:
>>> class address(base):
… __tablename__ = ‘addresses’
… id = column(integer, primary_key=true)
… email_address = column(string(50), nullable=false)
… user_id = column(integer, foreignkey(‘users.id’))
… user = relationship(“user”, back_populates=”addresses”)
…
… def __repr__(self):
… return “” % self.email_address
now when we load the user jack (below using get(), which loads by primary key), removing an address from the corresponding addresses collection will result in that address being deleted:
# load jack by primary key
>>> jack = session.query(user).get(5)
# remove one address (lazy load fires off)
>>> del jack.addresses[1]
# only one address remains
>>> session.query(address).filter(
… address.email_address.in_([‘jack@google.com’, ‘j25@yahoo.com’])
… ).count()
1
deleting jack will delete both jack and the remaining address associated with the user:
>>> session.delete(jack)
>>> session.query(user).filter_by(name=’jack’).count()
0
>>> session.query(address).filter(
… address.email_address.in_([‘jack@google.com’, ‘j25@yahoo.com’])
… ).count()
0
further detail on configuration of cascades is at cascades. the cascade functionality can also integrate smoothly with the on delete cascade functionality of the relational database. see using passive deletes for details.
backref
上面同时设置两个relationship太麻烦了,可以使用backref
from sqlalchemy import integer, foreignkey, string, column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
base = declarative_base()
class user(base):
__tablename__ = ‘user’
id = column(integer, primary_key=true)
name = column(string)
addresses = relationship(“address”, backref=”user”)
class address(base):
__tablename__ = ‘address’
id = column(integer, primary_key=true)
email = column(string)
user_id = column(integer, foreignkey(‘user.id’))
the above configuration establishes a collection of address objects on user called user.addresses. it also establishes a .user attribute on address which will refer to the parent user object.
in fact, the backref keyword is only a common shortcut for placing a second relationship() onto the address mapping, including the establishment of an event listener on both sides which will mirror attribute operations in both directions. the above configuration is equivalent to:
rom sqlalchemy import integer, foreignkey, string, column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
base = declarative_base()
class user(base):
__tablename__ = ‘user’
id = column(integer, primary_key=true)
name = column(string)
addresses = relationship(“address”, back_populates=”user”)
class address(base):
__tablename__ = ‘address’
id = column(integer, primary_key=true)
email = column(string)
user_id = column(integer, foreignkey(‘user.id’))
user = relationship(“user”, back_populates=”addresses”)
above, we add a .user relationship to address explicitly. on both relationships, the back_populates directive tells each relationship about the other one, indicating that they should establish “bidirectional” behavior between each other. the primary effect of this configuration is that the relationship adds event handlers to both attributes which have the behavior of “when an append or set event occurs here, set ourselves onto the incoming attribute using this particular attribute name”. the behavior is illustrated as follows. start with a user and an address instance. the .addresses collection is empty, and the .user attribute is none:
>>> u1 = user()
>>> a1 = address()
>>> u1.addresses
[]
>>> print(a1.user)
none
however, once the address is appended to the u1.addresses collection, both the collection and the scalar attribute have been populated:
>>> u1.addresses.append(a1)
>>> u1.addresses
[]
>>> a1.user
this behavior of course works in reverse for removal operations as well, as well as for equivalent operations on both sides. such as when .user is set again to none, the address object is removed from the reverse collection:
>>> a1.user = none
>>> u1.addresses
[]
the manipulation of the .addresses collection and the .user attribute occurs entirely in python without any interaction with the sql database. without this behavior, the proper state would be apparent on both sides once the data has been flushed to the database, and later reloaded after a commit or expiration operation occurs. the backref/back_populates behavior has the advantage that common bidirectional operations can reflect the correct state without requiring a database round trip.
remember, when the backref keyword is used on a single relationship, it’s exactly the same as if the above two relationships were created inpidually using back_populates on each.
mysql操作
检验一下我们上面的成果以及熟悉创建的mysql表的结构
地址表的结构
> show create table addresses;
+———–+—————-+
| table | create table |
|———–+—————-|
| addresses | create table `addresses` (
`id` int(11) not null auto_increment,
`email_address` varchar(50) not null,
`user_id` int(11) default null,
primary key (`id`),
key `user_id` (`user_id`),
constraint `addresses_ibfk_1` foreign key (`user_id`) references `users` (`id`)
) engine=innodb auto_increment=5 default charset=utf8 |
+———–+—————-+
1 row in set
time: 0.005s
> desc addresses;
+—————+————-+——–+——-+———–+—————-+
| field | type | null | key | default | extra |
|—————+————-+——–+——-+———–+—————-|
| id | int(11) | no | pri | | auto_increment |
| email_address | varchar(50) | no | | | |
| user_id | int(11) | yes | mul | | |
+—————+————-+——–+——-+———–+—————-+
3 rows in set
time: 0.002s
用户表的结构
> show create table users;
+———+—————-+
| table | create table |
|———+—————-|
| users | create table `users` (
`id` int(11) not null auto_increment,
`name` varchar(50) default null,
`fullname` varchar(50) default null,
`password` varchar(50) default null,
primary key (`id`)
) engine=innodb auto_increment=6 default charset=utf8 |
+———+—————-+
1 row in set
time: 0.002s
> desc users;
+———-+————-+——–+——-+———–+—————-+
| field | type | null | key | default | extra |
|———-+————-+——–+——-+———–+—————-|
| id | int(11) | no | pri | | auto_increment |
| name | varchar(50) | yes | | | |
| fullname | varchar(50) | yes | | | |
| password | varchar(50) | yes | | | |
+———-+————-+——–+——-+———–+—————-+
4 rows in set
time: 0.003s
详细数据
> select * from addresses;
+——+—————–+———–+
| id | email_address | user_id |
|——+—————–+———–|
| 3 | jack@google.com | 5 |
| 4 | j25@yahoo.com | 5 |
+——+—————–+———–+
2 rows in set
time: 0.002s
> select * from users;
+——+——–+—————-+————+
| id | name | fullname | password |
|——+——–+—————-+————|
| 1 | ed | ed jones | f8s7ccs |
| 2 | wendy | wendy williams | foobar |
| 3 | mary | mary contrary | xxg527 |
| 4 | fred | fred flinstone | blah |
| 5 | jack | jack bean | gjffdd |
+——+——–+—————-+————+
5 rows in set
time: 0.003s知乎live设计模型from sqlalchemy import column, string, integer, create_engine, smallinteger
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
db_uri = ‘sqlite:///user.db’
base = declarative_base()
engine = create_engine(db_uri)
base.metadata.bind = engine
session = sessionmaker(bind=engine)
session = session()class user(base):
__tablename__ = ‘live_user’
id = column(integer, unique=true, primary_key=true, autoincrement=true)
speaker_id = column(string(40), index=true, unique=true)
name = column(string(40), index=true, nullable=false)
gender = column(smallinteger, default=2)
headline = column(string(200))
avatar_url = column(string(100), nullable=false)
bio = column(string(200))
description = column(string())
@classmethod
def add(cls, **kwargs):
speaker_id = kwargs.get(‘speaker_id’, none)
if id is not none:
r = session.query(cls).filter_by(speaker_localhost’])class live(doctype):
id = integer()
speaker_id = integer()
feedback_score = float() # 评分
topic_names = text(analyzer=’ik_max_word’) # 话题标签名字
seats_taken = integer() # 参与人数
subject = text(analyzer=’ik_max_word’) # 标题
amount = float() # 价格(rmb)
description = text(analyzer=’ik_max_word’)
status = boolean() # public(true)/ended(false)
starts_at = date()
outline = text(analyzer=’ik_max_word’) # live内容
speaker_message_count = integer()
tag_names = text(analyzer=’ik_max_word’)
liked_num = integer()
class meta:
index = ‘live’
@classmethod
def add(cls, **kwargs):
id = kwargs.pop(‘id’, none)
if id is none:
return false
live = cls(meta={‘id’: id}, **kwargs)
live.save()
return live
它允许我们用一种非常可维护的方法来组织字典:
in : from elasticsearch_dsl.query import q
in : q(‘multi_match’, subject=’python’).to_dict()
out: {‘multi_match’: {‘subject’: ‘python’}}in : from elasticsearch import elasticsearch
in : from elasticsearch_dsl import search, q
in : s = search(using=client, index=’live’)
in : s = s.query(‘match’, subject=’python’).query(~q(‘match’, description=’量化’))
in : s.execute()
out: