【问题标题】:Sqlacodegen generates mixed models and tablesSqlacodegen 生成混合模型和表
【发布时间】:2016-01-08 11:08:16
【问题描述】:

执行这个命令:

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

db.py 包含生成的表:

t_table1 = Table(...)

还有课程:

Table2(Base):
    __tablename__ = 'table2'

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

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

【问题讨论】:

    标签: python sqlalchemy sqlacodegen


    【解决方案1】:

    看起来您所描述的内容本身就是一项功能。 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 中指出

    如果一个表满足所有 以下条件:

    1. 正好有两个外键约束
    2. 它的所有列都包含在所述约束中

    不过,您可以尝试快速而肮脏的 hack。在源代码中找到这些行(类似于/.../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 标志。

    【讨论】:

    • SQLAlchemy 要求每个映射类都有一个主键,所以即使有这样的选项,生成的模型代码也不起作用。
    • @AlexGrönholm 那么在 sqlalchemy 中访问没有主键的现有表的最佳做法是什么?
    • 您可以使用 Table 对象(SQLAlchemy 文档应该涵盖这一点),它们只是不能映射为类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    相关资源
    最近更新 更多