繁体   English   中英

如何使用sqlmodel在现有数据库中创建表

[英]How to create table in existing database with sqlmodel

我正在通过此链接https://sqlmodel.tiangolo.com/tutorial/connect/create-connected-tables/创建我的 sqlite 数据库表。

现在,这会在我的 FastAPI 应用程序启动时创建两个表TeamHero 但在特殊用例中,我可能需要创建另一个新表。

我当然可以通过以下方式做到这一点

def create_specific_table():
    conn = engine.connect()
    conn.execute(
        """ CREATE TABLE IF NOT EXISTS table2 ( 
            key TEXT PRIMARY KEY,  
            execution_id TEXT,
            )"""
          )

但我想用 Model class 来做。# models/table2.py

from sqlmodel import Column, SQLModel
class Table2(SQLModel, table=True):
    key: str = Field(default=None, foreign_key="table1.id")
    execution_id: str = Field(title="My Execution ID", index=False, default=None)

然后

def create_specific_table():
    import db.engine # Using the same engine
    SQLModel.metadata.create_all(engine) 

但它没有创建Table2

我还尝试将表传递给create_all表列表

def create_specific_table():
    import db.engine # Using the same engine
    SQLModel.metadata.create_all(engine, tables=[Table1, Table2])

但是低于错误

Traceback (most recent call last):
  File "pydantic/validators.py", line 709, in pydantic.validators.find_validators
TypeError: issubclass() arg 1 must be a class



sqlmodel/main.py", line 277, in __new__
    new_cls = super().__new__(cls, name, bases, dict_used, **config_kwargs)
  File "pydantic/main.py", line 205, in pydantic.main.ModelMetaclass.__new__
  File "pydantic/fields.py", line 491, in pydantic.fields.ModelField.infer
  File "pydantic/fields.py", line 421, in pydantic.fields.ModelField.__init__
  File "pydantic/fields.py", line 542, in pydantic.fields.ModelField.prepare
  File "pydantic/fields.py", line 804, in pydantic.fields.ModelField.populate_validators
  File "pydantic/validators.py", line 718, in find_validators
RuntimeError: error checking inheritance of FieldInfo(extra={}) (type: FieldInfo)

我在main.py中触发 db model 创建的方式基本上是

@app.on_event("startup")
def on_startup():
    create_db_and_tables() # these are common
    create_specific_table() 

尝试:

    Table2.__table__.create(engine)

参考: 如何将 SQLModel 与 1 个以上的数据库一起使用?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM