sqlacodegen 生成混合模型和表

Sqlacodegen generates mixed models and tables

执行这条命令:

sqlacodegen <connection-url> --outfile db.py 

db.py 包含生成的 tables:

t_table1 = Table(...)

和class也是:

Table2(Base):
    __tablename__ = 'table2'

问题是 table 仅以一种方式生成 - table 或 class。

我想让它只生成模型(classes),但在提供的标志中我找不到这样的选项。有什么想法吗?

您所描述的似乎是一项功能本身。 sqlacodegen不会总是生成 class 个模型。

它将只为tables形成模型classes,它们有一个主键并且不是关联tables,因为你可以在 source code:

中看到
# Only form model classes for tables that have a primary key and are not association tables
if noclasses or not table.primary_key or table.name in association_tables:
    model = self.table_model(table)
else:
    model = self.class_model(table, links[table.name], self.inflect_engine, not nojoined)
    classes[model.name] = model

此外,在documentation中指出

A table is considered an association table if it satisfies all of the following conditions:

  1. has exactly two foreign key constraints
  2. all its columns are involved in said constraints

尽管如此,您可以尝试快速而肮脏的黑客攻击。在源代码中找到这些行(类似于 /.../lib/python2.7/site-packages/sqlacodegen/codegen.py)并注释掉前三行代码(并修正缩进):

# Only form model classes for tables that have a primary key and are not association tables
# if noclasses or not table.primary_key or table.name in association_tables:
#    model = self.table_model(table)
# else:
model = self.class_model(table, links[table.name], self.inflect_engine, not nojoined)
classes[model.name] = model

我已经针对一个作为 table 模型生成的特定 table 进行了尝试。它来自

t_Admin_op = Table(
    'Admin_op', metadata,
    Column('id_admin', Integer, nullable=False),
    Column('id_op', Integer, nullable=False)
)

class AdminOp(Base):
    __tablename__ = 'Admin_op'

    id_admin = Column(Integer, nullable=False)
    id_op = Column(Integer, nullable=False)

您也可以在 official tracker.

中将此问题作为功能请求打开

以防万一,如果您想要相反的(仅限 table 型号),您可以使用 --noclasses 标志。