Default values for fields not working as expected with SQLModel in PostgreSQL #1452
Privileged issue
Issue ContentI'm encountering an issue where default values for fields in my SQLModel class are not being applied when using PostgreSQL. Despite specifying default or default_factory for various fields, the database does not seem to handle these defaults, and errors occur during table creation or insertion. from datetime import datetime
from sqlmodel import Field, SQLModel
from typing import Optional
class Posts(SQLModel, table=True):
id: Optional[int] = Field(default_factory=int, primary_key=True)
title: str
content: str
published: Optional[bool] = Field(default_factory=lambda: True)
created_at: Optional[datetime] = Field(default_factory=datetime.now) |
Answered by
ArazHeydarov
Mar 16, 2025
Replies: 1 comment
|
post = Posts(title="Some title", content="Some Content")
assert post.id == 0If you go directly to the Postgres DB and try to add a row there, these defaults won't be considered. |
0 replies
Answer selected by
YuriiMotov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
defaultanddefault_factoryarguments are only Python-level defaults. They'll assign a default value to your field only during the creation of instances in Python.If you go directly to the Postgres DB and try to add a row there, these defaults won't be considered.
In order to enforce the default in DB level, you can use
sa_column_kwargs={"server_default": "<value>"}argument.I hope this will solve your issue.