這是我參與更文挑戰的第8天,活動詳情查看: 更文挑戰python
今天介紹一個後臺開發神器,很適合當咱們數據庫中已存在了這些表,而後你想獲得它們的model類使用ORM技術進行CRUD操做(或者我根本就不知道怎麼寫modle類的時候);
手寫100張表的model類?
這是。。。。。。。。。 是不可能的,這輩子都不可能的。
由於咱們有sqlacodegen神器, 一行命令獲取數據庫全部表的模型類。mysql
一、後臺開發中,須要常常對數據庫進行CRUD操做;sql
二、這個過程當中,咱們就常常藉助ORM技術進行便利的CURD,好比成熟的SQLAlchemy;數據庫
三、可是,進行ORM操做前須要提供和table對應的模型類;markdown
四、而且,不少歷史table已經存在於數據庫中;app
五、若是有幾百張table呢?還本身一個個去寫嗎?less
六、我相信你心中會有個念頭。。。post
仍是那句話,Python大法好。 這裏就介紹一個根據已有數據庫(表)結構生成對應SQLAlchemy模型類的神器: sqlacodegenui
This is a tool that reads the structure of an existing database and generates the appropriate SQLAlchemy model code, using the declarative style if possible.this
安裝方法:
pip install sqlacodegen
複製代碼
使用方法也很簡單,只須要在終端(命令行窗口)運行一行命令便可, 將會獲取到整個數據庫的model:
經常使用數據庫的使用方法:
sqlacodegen postgresql:///some_local_db
sqlacodegen mysql+oursql://user:password@localhost/dbname
sqlacodegen sqlite:///database.db
複製代碼
查看具體參數能夠輸入:
sqlacodegen --help
複製代碼
參數含義:
optional arguments:
-h, --help show this help message and exit
--version print the version number and exit
--schema SCHEMA load tables from an alternate schema
--tables TABLES tables to process (comma-separated, default: all)
--noviews ignore views
--noindexes ignore indexes
--noconstraints ignore constraints
--nojoined don't autodetect joined table inheritance
--noinflect don't try to convert tables names to singular form
--noclasses don't generate classes, only tables
--outfile OUTFILE file to write output to (default: stdout)
複製代碼
目前我在postgresql的默認的postgres數據庫中有個這樣的表:
create table friends
(
id varchar(3) primary key ,
address varchar(50) not null ,
name varchar(10) not null
);
create unique index name_address
on friends (name, address);
複製代碼
爲了使用ORM進行操做,我須要獲取它的modle類但惟一索引的model類怎麼寫呢? 咱們藉助sqlacodegen來自動生成就行了
sqlacodegen postgresql://ridingroad:ridingroad@127.0.0.1:5432/postgres --outfile=models.py --tables friends
複製代碼
查看輸出到models.py的內容
# coding: utf-8
from sqlalchemy import Column, Index, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Friend(Base):
__tablename__ = 'friends'
__table_args__ = (
Index('name_address', 'name', 'address', unique=True),
)
id = Column(String(3), primary_key=True)
address = Column(String(50), nullable=False)
name = Column(String(10), nullable=False)
複製代碼
若是你有不少表,就直接指定數據庫唄(這是會生成整個數據庫的ORM模型類哦),不具體到每張表就行了, 後面就能夠愉快的CRUD了,耶
Why does it sometimes generate classes and sometimes Tables?
Unless the --noclasses option is used, sqlacodegen tries to generate declarative model classes from each table. There are two circumstances in which a Table is generated instead: 一、the table has no primary key constraint (which is required by SQLAlchemy for every model class) 二、the table is an association table between two other tables
當你的表的字段缺乏primary key或這張表是有兩個外鍵約束的時候,會生成table而不是模型類了。好比,我那張表是這樣的結構:
create table friends
(
id varchar(3) ,
address varchar(50) not null ,
name varchar(10) not null
);
create unique index name_address
on friends (name, address);
複製代碼
再執行同一個命令:
sqlacodegen postgresql://ridingroad:ridingroad@127.0.0.1:5432/postgres --outfile=models.py --tables friends
複製代碼
獲取到的是Table:
# coding: utf-8
from sqlalchemy import Column, Index, MetaData, String, Table
metadata = MetaData()
t_friends = Table(
'friends', metadata,
Column('id', String(3)),
Column('address', String(50), nullable=False),
Column('name', String(10), nullable=False),
Index('name_address', 'name', 'address', unique=True)
)
複製代碼
其實和模型類差很少嘛,可是仍是儘可能帶上primary key吧,省得手動修改爲模型類