Wednesday, 22 March 2023

Dynamically set sql-default value with table-name in SQLModel

I'm trying to create a base-class in SQLModel which looks like this:

class BaseModel(SQLModel):
    @declared_attr
    def __tablename__(cls) -> str:
        return cls.__name__

    guid: Optional[UUID] = Field(default=None, primary_key=True)

class SequencedBaseModel(BaseModel):
    sequence_id: str = Field(sa_column=Column(VARCHAR(50), server_default=text(f"SELECT '{TABLENAME}_' + convert(varchar(10), NEXT VALUE FOR dbo.sequence)")))

so I got a table like this:

class Project(SequencedBaseModel):
    ...

where alembic would generate a migration for a table Project with columns guid and sequence_id. The default-value for sequence-id is a sequence which is generated with

SELECT '{TABLENAME}_' + convert(varchar(10), NEXT VALUE FOR dbo.sequence)

and should insert into project-table the values Project_1, Project_2, ...

Any idea on how to set the tablename dynamically? I cannot use a constructor for setting the columns because alembic is ignoring them, I cannot access the __tablename__() function, or cls, because the columns are static...



from Dynamically set sql-default value with table-name in SQLModel

No comments:

Post a Comment