pythonsqlmodel

Auto increment string primary key with custom logic in sqlmodel


I have a sqlmodel class:

from typing import Optional, List
from sqlmodel import Field, SQLModel, UniqueConstraint

class Query(SQLModel, table=True):
    id: Optional[str] = Field(default=None, primary_key=True)
    text: str = Field(default=None, unique=True)
    task: str 
    use_case: str

I would like to have an auto increment with custom logic, for example :

# latest_id is an int that increment
new_id = f'{task[0:3]}-{use_case[0:3]}-{latest_id}'

I can implement a helper function that create that id but I would like to have this logic inside the class.
Thank you


Solution

  • After some research, it seems that this is impossible. My solution consists of an additional getter which generates a denormalized id.