Python后台开发ORM模型类自动生成神器

这是我参与更文挑战的第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吧,省得手动修改为模型类

相关文章
相关标签/搜索