当前位置:  开发笔记 > 编程语言 > 正文

Sqlacodegen生成混合模型和表格

如何解决《Sqlacodegen生成混合模型和表格》经验,为你挑选了1个好方法。

执行此命令:

sqlacodegen  --outfile db.py 

db.py包含生成的表:

t_table1 = Table(...)

和班级:

Table2(Base):
    __tablename__ = 'table2'

问题是表只以一种方式生成 - 表或类.

我想让它只生成模型(类),但在提供的标志中我找不到这样的选项.任何的想法?



1> iled..:

看起来你所描述的是一个功能本身.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标志.


SQLAlchemy对于每个映射的类都需要一个主键,因此,即使有这样的选项,生成的模型代码也无法使用。
推荐阅读
U友50081205_653
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有