I have a FastAPI application and in my Item
table the field id
is an uuid
. I'm wondering if I should handle the automatic assigning of id
in my models.py
or in the Alembic
migration file?
At the moment this is what I have in my models:
class ItemDb(SQLMODEL, table=True):
__tablename__ = "items"
id: str = Field(
default_factory=uuid.uuid4, primary_key=True, index=True, nullable=False
)
In the migration file I have this:
sa.Column("id", sa.String(), nullable=False),
Is this a good way to handle the id or is there a better way, e.g. can I set the Postgres automatically assign an uuid
when a new row is inserted?
Edit. I tried this:
Model:
class ItemDb(SQLMODEL, table=True):
__tablename__ = "items"
id: str = Field(
primary_key=True, index=True, nullable=False
)
Migration:
sa.Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4),
This gives me an error because the id
is now None
.