2016-01-08 66 views
0

執行此命令:Sqlacodegen生成混合模型和表

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

的db.py包含生成的表:

t_table1 = Table(...) 

和類太:

Table2(Base): 
    __tablename__ = 'table2' 

的問題是一個表格只能以一種方式生成 - 無論是表格還是類別。

我想使它只生成模型(類),但在提供的標誌我找不到這樣的選項。任何想法?

回答

5

它看起來像你描述的是一個功能本身。 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. 所有列涉及表示約束

雖然,你可以嘗試一個快速和骯髒的黑客。找到源代碼(類似於/.../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標誌。