sqlalchemy的常用功能列举
自己使用的心得总结
创建orm模型的固定模板
from sqlalchemy import create_engine, Column, Integer, Text, ForeignKey, Date, Boolean
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('sqlite:///data.db') # 如想用其他数据库请参考官方文档
Session = sessionmaker(bind=engine)
session = Session()
ss = session # 我比较喜欢用ss
class Table(Base):
__tablename__ = 'table' # 这个是在数据库中真正显示的名字
id = Column(Integer, primary_key=True)
...
Base.metadata.create_all(engine) # 在实际的数据库中根据你前面定义的模型来创建表
建立orm模型时的相关方法
一对多
class Son(Base):
parent_id = Column(Integer, ForeignKey('parent.id'), default=0)
parent = relationship('Parent', backref='sons')
在Son
的定义里增加一个外键,用来保存他的parent.id
,同时建立二者的一个relationship
,这一项不对应数据库中的键,只是告诉模型相关的关系信息。
如果对应的
parent
没有被建立,则可直接用字符串来表示 设置backref
可以让parent
访问到sons
多对多
class Item(Base):
tag_refs = relationship('Tag', secondary='items2tags', backref='Images')
class Images2Tags(Base):
__tablename__ = 'images2tags'
id = Column(Integer, primary_key=True, autoincrement=True)
game_id = Column(Integer, ForeignKey('image.id'))
tag_name = Column(Integer, ForeignKey('tag.name'))
二者之一的字段中添加上一个relationship
,设置一个secondary
来存放二者间的关系,设置backref
同样让另一边可以访问到。
然后在secondary
的定义上,定义两个外键即可,无需其他
query查询
插入数据
防止数据重复
class Tag(Base):
__tablename__ = 'tag'
name = Column(Text, primary_key=True, nullable=False)
@classmethod
def get_unique(cls, name):
# get the session cache, creating it if necessary
cache = session._unique_cache = getattr(session, '_unique_cache', {})
# create a key for memorizing
key = (cls, name)
# check the cache first
o = cache.get(key)
if o is None:
# check the database if it's not in the cache
o = session.query(cls).filter_by(name=name).first()
if o is None:
# create a new one if it's not in the database
o = cls(name=name)
session.add(o)
# update the cache
cache[key] = o
return o
如此若要创建一条数据,使用Tag.get_unique(name='xxx')
,就不再需要担心这个数据的重复问题了
最后修改于 2024-10-07