python用sqlacodegen根据已有数据库(表)结构生成对应SQLAlchemy模型

作者:一撸程猿 时间:2024-01-23 02:39:44 

目录
  • 应用场景

  • 福音

  • 快快使用

  • 模型类效果

  • 注意事项

今天介绍一个后台开发神器,很适合当我们数据库中已存在了这些表,然后你想得到它们的model类使用ORM技术进行CRUD操作(或者我根本就不知道怎么写modle类的时候);
手写100张表的model类?
这是。。。。。。。。。 是不可能的,这辈子都不可能的。
因为我们有sqlacodegen神器, 一行命令获取数据库所有表的模型类。

应用场景

1、后台开发中,需要经常对数据库进行CRUD操作;

2、这个过程中,我们就经常借助ORM技术进行便利的CURD,比如成熟的SQLAlchemy;

3、但是,进行ORM操作前需要提供和table对应的模型类;

4、并且,很多历史table已经存在于数据库中;

5、如果有几百张table呢?还自己一个个去写吗?

6、我相信你心中会有个念头。。。

福音

还是那句话,Python * 好。 这里就介绍一个根据已有数据库(表)结构生成对应SQLAlchemy模型类的神器: sqlacodegen

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.

安装方法:


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: 1、the table has no primary key constraint (which is required by SQLAlchemy for every model class) 2、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吧,免得手动修改成模型类

来源:https://juejin.cn/post/6971369096378056741

标签:python,sqlacodegen,orm,SQLAlchemy
0
投稿

猜你喜欢

  • python字符串替换第一个字符串的方法

    2021-08-16 13:55:47
  • python中将字典形式的数据循环插入Excel

    2023-07-05 01:49:19
  • 教你精确编写高质量高性能的MySQL语法

    2009-01-14 12:57:00
  • 简单了解操作mysql数据库的命令行神器mycli

    2024-01-24 03:44:14
  • 解决Python内层for循环如何break出外层的循环的问题

    2023-09-07 22:21:39
  • PHP登录验证功能示例【用户名、密码、验证码、数据库、已登陆验证、自动登录和注销登录等】

    2023-11-14 23:24:02
  • 全面解读Python Web开发框架Django

    2022-06-24 19:41:45
  • 记录PHP错误日志 display_errors与log_errors的区别

    2023-11-14 09:38:29
  • 浅述七大主流数据库

    2011-08-05 18:21:27
  • PYTHON实现SIGN签名的过程解析

    2021-08-09 13:29:05
  • python计算牛顿迭代多项式实例分析

    2022-10-27 05:32:37
  • centos 安装mysql中遇到问题的解决办法

    2010-12-14 15:11:00
  • 详解Python Flask框架的安装及应用

    2022-06-20 11:12:50
  • python 中 lxml 的 etree 标签解析

    2023-02-26 02:59:37
  • 如何把一长串数字分位显示?

    2009-11-06 14:01:00
  • Go 值传递与引用传递的方法

    2023-06-25 03:11:11
  • BERT vs GPT自然语言处理中的关键差异详解

    2022-04-01 08:15:36
  • Linux系统中MySQL的常用操作命令

    2024-01-18 22:00:10
  • 使用pandas库对csv文件进行筛选保存

    2022-12-25 04:55:10
  • 浅谈python已知元素,获取元素索引(numpy,pandas)

    2023-08-04 16:01:00
  • asp之家 网络编程 m.aspxhome.com