Skip to content

How to dynamically create tables by sqlmodel? #1473

Discussion options

You must be logged in to vote

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.

import asyncio
from typing import Optional

import pytest
import pytest_asyncio
from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Field, SQLModel


class Tusns(SQLModel, table=True):
    __tablename__ = "tusns"

    id: int = Field(primary_key=True, nullable=False)


def devic…

Replies: 7 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
5 participants
Converted from issue

This discussion was converted from issue #377 on August 08, 2025 16:26.