gpt4 book ai didi

python - sqlacodegen 生成混合模型和表

转载 作者:太空狗 更新时间:2023-10-30 01:50:42 29 4
gpt4 key购买 nike

执行这条命令:

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

db.py 包含生成的表:

t_table1 = Table(...)

还有类:

Table2(Base):
__tablename__ = 'table2'

问题是表只能以一种方式生成 - 要么是表,要么是类。

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

最佳答案

看起来您所描述的是一项功能本身。 sqlacodegen不会总是生成类模型。

只会为具有主键但不是关联表的表形成模型类,如您在 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

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

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 中将此问题作为功能请求打开.

以防万一,如果你想要相反的东西(只有表格模型),你可以使用 --noclasses 标志。

关于python - sqlacodegen 生成混合模型和表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34675604/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com