执行此命令:
sqlacodegen--outfile db.py
db.py包含生成的表:
t_table1 = Table(...)
和班级:
Table2(Base): __tablename__ = 'table2'
问题是表只以一种方式生成 - 表或类.
我想让它只生成模型(类),但在提供的标志中我找不到这样的选项.任何的想法?
看起来你所描述的是一个功能本身.sqlacodegen
不会总是生成类模型.
它只会为具有主键且不是关联表的表形成模型类,如源代码中所示:
# 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
此外,在文件中说明了这一点
如果表满足以下所有条件,则表被视为关联表:
有两个外键约束
它的所有列都涉及所述约束
虽然,你可以尝试一个快速和肮脏的黑客.在源代码中找到这些行(类似于/.../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)
您还可以在官方跟踪器中打开有关此问题的问题作为功能请求.
为了以防万一,如果你想要相反的(只有表模型),你可以使用--noclasses
标志.