How to Use Anti-launched models based on sqlalchemy inside the database tables, and then query

About sqlalchemy mapping database inside the table, under normal circumstances we need to define a model to map database inside the table. But many times inside the database tables are defined, and many fields, is there not define the model, but also use it to find data orm syntax?

Obviously it is, here we come to try, first of all in my local database, a total of two tables, a table called the girls, another is called info.

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/8/13 11:32
from sqlalchemy import MetaData
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker

# 定义引擎,不用说
engine = create_engine("postgresql://postgres:zgghyys123@localhost:5432/postgres")
# 绑定引擎,生成一个MetaData对象
metadata = MetaData(bind=engine)
# 通过engine将tables反射到meta上,指定schema,这里就是public,public的话在postgresql里面不需要指定,默认的
# only参数则是提取我们指定的表
metadata.reflect(engine, only=["girls"], schema="public")
# 调用automap_base,传入metadata,从名字也能看出来,自动映射成类
# 将metadata里面保存的表信息映射成Base
Base = automap_base(metadata=metadata)
# 调用prepare方法,设置被映射的类和关系
Base.prepare()

# 然后数据库里里面的表都被映射类之后,被保存在Base.classes下面,直接通过Base.classes.表名 即可得到模型
# 比如我们的是girls表,那么获取对应的类,就可以使用Base.classes.girls,我们起名为Girls
# 这个Girls和我们使用class Girls(Base):这种以前使用的方式得到的Girls是一样的
# 只不过我们以前是先定义模型然后映射成表,这里是由表反过来推出模型
Girls = Base.classes.girls

# 那么就可以创建session了
# 创建session的方式还是和以前一样,没什么区别
Session = sessionmaker()
session = Session(bind=engine)

# 查询
res = session.query(Girls).first()
print(res.id, res.name, res.age, res.gender)  # 6 芙兰朵露斯卡雷特 495 女

But if the table more, then, we can not specify only, it will acquire all of the table

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/8/13 11:32
from sqlalchemy import MetaData
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker

engine = create_engine("postgresql://postgres:zgghyys123@localhost:5432/postgres")
metadata = MetaData(bind=engine)
# 不指定only
metadata.reflect(engine, schema="public")
Base = automap_base(metadata=metadata)
Base.prepare()

# 此时的Base.classes则是储存了数据库里面所有的表对应的模型
Info = Base.classes.info

Session = sessionmaker()
session = Session(bind=engine)

res = session.query(Info).first()
print(res.id, res.anime, res.boyfriend)  # 2 樱花庄的宠物女孩 神田空太

The benefits of this inquiry is that we used to manually define the model to match the tables inside the database, you must have a primary key, but now do not need a database inside the table has no primary key can be.

Of course, the way we define the model, can also be a large number of simplified

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/8/13 13:19
from sqlalchemy import MetaData
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Table

engine = create_engine("postgresql://dev:[email protected]:5dsa3/metro")
Base = declarative_base(bind=engine)
metadata = MetaData(bind=engine)
metadata.reflect(engine, schema="th")


class Fucker(Base):
    # 以前指定__tablename__ = "staff"
    # 这里指定__table__ = Table("staff", metadata, autoload=True)
    __table__ = Table("staff", metadata, autoload=True, schema="th")


Session = sessionmaker(bind=engine)
session = Session()

for res in session.query(Fucker)[: 10]:
    print(res.name, res.oid, res.id, res.post)
    """
    阙海云 TH021310 01010003703 信号工
    严旻炜 TH021310 01010009076 信号工
    黄雯婷 TH021310 01010003624 信号工
    张翥婧 TH220002 01010002897 商务管理
    钱林军 TH021310 01010003028 信号副班组长
    赵秋蓉 TH150002 01010003089 副班组长
    余静 TH150002 01010008497 副班组长
    付洋 TH150002 01010003919 副班组长
    徐倩玉 TH021310 01010009096 信号工
    吴绮平 TH01- 01010002871 副经理
    """

However, this approach is not recommended, not only did the first method is simple, and it will pop up a warning as to what warning did not see the source code, is unclear. However, the above method is absolutely no problem, but also high efficiency. Just inside the database tables and more, be sure to add only the parameters, because without it, will map all the tables

How to use sqlalchemy determine whether there is a particular table, and all the tables in the current schema queries under a current database schema which

from sqlalchemy import create_engine

engine = create_engine("postgresql://dev:[email protected]/metro")
print(engine.has_table(table_name="staff", schema="th"))  # True

all_tables = engine.table_names(schema="th")  # True
print(all_tables)
"""
['staff_detail', 'image_base_config', 'patrol', 
'attendance_config', 'new_org', 'attendance_daily', 
'attendance_monthly', 'staff', 'post', 'order_config',
'order', 'construction_plan', 'patrol_config', 
'record_detail', 'record_info', 'documentary_config', 
'degree', '_attendance_original_import', 'attendance_original', 
'org2', '_ceshi', 'org2_bak', '_dingding_dep', 
'org_copy1', 'org', 'org2_bak1']
"""
print("staff" in all_tables)  # True

Guess you like

Origin www.cnblogs.com/traditional/p/11345422.html