0

I am using SQLModel with FastAPI to insert data into Postgres.

The model I am using is

import uuid
from datetime import datetime, time
from typing import Optional
from uuid import UUID

from sqlmodel import Field, SQLModel, create_engine, Column, DateTime, JSON, text, MetaData

from sqlalchemy.dialects.postgresql import UUID as UUIDSA

class LogsSessionSqlModel(SQLModel, table=True):
  __tablename__ = "foo"
  metadata = foo_metadata

  id: Optional[int] = Field(primary_key=True, index=True)
  description: str = Field(nullable=False, max_length=1024)
  created: Optional[datetime] = Field(sa_column=Column(DateTime(timezone=True),   nullable=False))
  uid: Optional[UUID] = Field(index=True, nullable=False, default=uuid.uuid4())

And this is the matching Postgres table.

Postgres Table Columns

If I don't provide the default value for uid, I get an error that the value cannot be null and if I provide a value, then Postgres is not the one to create it.

What is incorrect with the definition of uid field to make it so I don't have to provide a value when I insert a new line and let Postgres auto generate a value?

RaamEE
  • 3,017
  • 4
  • 33
  • 53

1 Answers1

1

This is the proper setting for the uid field of the table class.

Once I use the sa_column (SqlAlchemy column) in this way, then Postgres is providing the value as expected.

import uuid
from datetime import datetime, time
from typing import Optional
from uuid import UUID

from sqlmodel import Field, SQLModel, create_engine, Column, DateTime, JSON, text, MetaData

from sqlalchemy.dialects.postgresql import UUID as UUIDSA


class LogsSessionSqlModel(SQLModel, table=True):
  __tablename__ = "sessions"
  metadata = logs_metadata
  __table_args__ = {'extend_existing': True}

  id: Optional[int] = Field(primary_key=True, index=True)
  description: str = Field(nullable=False, max_length=1024)
  created: Optional[datetime] = Field(sa_column=Column(DateTime(timezone=True), nullable=False))
  completed: Optional[datetime] = Field(
      sa_column=Column(DateTime(timezone=True), nullable=True)
  )
  uid: Optional[UUID] = Field(
      sa_column=Column(
          UUIDSA(as_uuid=True),
          server_default=text("gen_random_uuid()")
      ), default=None
  )
RaamEE
  • 3,017
  • 4
  • 33
  • 53