I am creating a my sqlite Database tables following this link https://sqlmodel.tiangolo.com/tutorial/connect/create-connected-tables/ .
Now this creates two tables Team
and Hero
on start up of my FastAPI application. But on a special use-case I may need to create another new table.
I can certainly do that by following
def create_specific_table():
conn = engine.connect()
conn.execute(
""" CREATE TABLE IF NOT EXISTS table2 (
key TEXT PRIMARY KEY,
execution_id TEXT,
)"""
)
But I want to do it using the 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)
And then
def create_specific_table():
import db.engine # Using the same engine
SQLModel.metadata.create_all(engine)
But its not creating Table2
.
I tried also passing the table to create_all
table lists
def create_specific_table():
import db.engine # Using the same engine
SQLModel.metadata.create_all(engine, tables=[Table1, Table2])
But getting below error
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)
The way I am triggering the db model creation in main.py
is basically
@app.on_event("startup")
def on_startup():
create_db_and_tables() # these are common
create_specific_table()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.