How PostgreSQL sequence can be mapped with a column using SqlModel? #1506
Answered
by
YuriiMotov
shailendrafaarms
asked this question in
Questions
First Check
Commit to Help
Example Codeclass Orders(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
order_number: str
item_name: str
item_price: floatDescriptionI have a model named Orders, where I need to implement PostgreSQL sequence which will generate an auto-increment alphanumeric order number. I tried searching but no luck on how to implement in SqlModel. I have found it for SqlAlchemy but don't know how to do in SqlModel. Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.4 Python Version3.7 Additional ContextNo response |
Answered by
YuriiMotov
Aug 12, 2025
Replies: 2 comments
|
(Old wrong answer deleted) You can try |
0 replies
|
You can specify it using order_number: Optional[str] = Field(
sa_column=Column(
Integer,
Sequence("order_number_seq", start=100, increment=2),
nullable=False,
)
)Runnable code example: from typing import Optional
from sqlmodel import (
Column,
Field,
Integer,
Sequence,
Session,
SQLModel,
create_engine,
select,
)
engine = create_engine("postgresql://postgres:mysecretpassword@127.0.0.1:5432/some_db")
class Orders(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
order_number: Optional[str] = Field(
sa_column=Column(
Integer,
Sequence("order_number_seq", start=100, increment=2),
nullable=False,
)
)
item_name: str
item_price: float
if __name__ == "__main__":
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(Orders(item_name="item 1", item_price=0.1))
session.add(Orders(item_name="item 2", item_price=0.2))
session.commit()
with Session(engine) as session:
orders = session.exec(select(Orders)).all()
print(orders)Output: |
0 replies
Answer selected by
YuriiMotov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can specify it using
sa_columnparameter:Runnable code example: