You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How to dynamically create tables by sqlmodel? #377
I used the GitHub search to find a similar issue and didn't find it.
I searched the SQLModel documentation, with the integrated search.
I already searched in Google "How to X in SQLModel" and didn't find any information.
I already read and followed all the tutorial in the docs and didn't find an answer.
I already checked if it is not related to SQLModel but to Pydantic.
I already checked if it is not related to SQLModel but to SQLAlchemy.
Commit to Help
I commit to help with one of those options 👆
Example Code
classDeviceStore(SQLModel):
""" Devices of one batch """# __abstract__ = Trueid: Optional[int] =Field(None, primary_key=True,
sa_column_kwargs={"autoincrement": True})
name: strclassDeviceBatch01(DeviceStore):
__tablename__="devicebatch01"classDeviceBatch02(DeviceStore):
__tablename__="devicebatch02"
Description
I'm new here and learning to use sqlmodel, it's really great, now I got a question which is how to use sqlmodel dynamically to create tables, all my tables have the same format, just the table names are different, like logtable_2205, logtable_2206, logtable_2207. . . could you guys provide some ideas? thanks a lot.
All defined tables(not model, need table=True) are stored in tables({tablename: Table} mapping) of MetaData in the SQLModel class. After you find the table you want, you only need to create that table.
@jaytang0923 looks like TypedDict helped with it. Type hinting is impossible with this example of writing code, but typeddict should help out (python 3.8+ in typing or typing-extension on 3.6+)
I had a similar problem with trying to create a factory function for abstract columns. I think the below should help solve the issue.
I added some tests below too that prints out the SQL during the table creation, you can see from that the tables/columns/primary key/foreign key creation.
Activity
Niccolum commentedon Jul 15, 2022
@jaytang0923 I think
typecan help with it.For example
DeviceBatch01 = type("DeviceBatch01", (DeviceStore,), {"__tablename__": "devicebatch01"})But this desire looks like you want something bad.
phi-friday commentedon Jul 17, 2022
All defined tables(not model, need table=True) are stored in tables({tablename: Table} mapping) of MetaData in the SQLModel class. After you find the table you want, you only need to create that table.
jaytang0923 commentedon Jul 18, 2022
thank you @Niccolum , as you suggested, i almost succeeded.the remaining question is how to link foreign keys by type?
take error:
column 'tusnid'): Can't generate DDL for NullType(); did you forget to specify a type on this Column?
what i need liks this:
tusnid: Optional[int] = Field(None, foreign_key="tusns.id", primary_key=True)Niccolum commentedon Jul 18, 2022
@jaytang0923 looks like TypedDict helped with it. Type hinting is impossible with this example of writing code, but typeddict should help out (python 3.8+ in typing or typing-extension on 3.6+)
Niccolum commentedon Jul 18, 2022
I saw on typeddict and thought, how to use it with your case. Now i have only one vision
LTMullineux commentedon Jul 28, 2023
I had a similar problem with trying to create a factory function for abstract columns. I think the below should help solve the issue.
I added some tests below too that prints out the SQL during the table creation, you can see from that the tables/columns/primary key/foreign key creation.
Running this script with pytest spits out the following DDL:
2023-07-28 16:28:00,827 INFO sqlalchemy.engine.Engine CREATE TABLE tusns ( id SERIAL NOT NULL, PRIMARY KEY (id) ) 2023-07-28 16:28:00,827 INFO sqlalchemy.engine.Engine [no key 0.00015s] () 2023-07-28 16:28:00,836 INFO sqlalchemy.engine.Engine CREATE TABLE device_batch_01 ( id SERIAL, name VARCHAR NOT NULL, PRIMARY KEY (id), FOREIGN KEY(id) REFERENCES tusns (id) ON DELETE CASCADE ) 2023-07-28 16:28:00,836 INFO sqlalchemy.engine.Engine [no key 0.00024s] () 2023-07-28 16:28:00,846 INFO sqlalchemy.engine.Engine CREATE TABLE device_batch_02 ( id SERIAL, name VARCHAR NOT NULL, PRIMARY KEY (id), FOREIGN KEY(id) REFERENCES tusns (id) ON DELETE CASCADE ) 2023-07-28 16:28:00,847 INFO sqlalchemy.engine.Engine [no key 0.00023s] () 2023-07-28 16:28:00,857 INFO sqlalchemy.engine.Engine CREATE TABLE device_batch_03 ( id SERIAL, name VARCHAR NOT NULL, PRIMARY KEY (id), FOREIGN KEY(id) REFERENCES tusns (id) ON DELETE CASCADE ) ...msftcangoblowm commentedon Jul 6, 2025
Demonstrates SQLModel classes with unique Python class names. Does not hardcode or mimic to_snake function.
discussions 604