I'm struggling to get the syntax to create a UUID field when creating a model in my FastAPI application. I'm using SQLModel.
So basically, my models.py file looks like this:
from datetime import datetime
from typing import Optional
import uuid
from sqlalchemy import Column, DateTime
from sqlalchemy.dialects import postgresql as psql
from sqlmodel import SQLModel, Field
class ModelBase(SQLModel):
"""
Base class for database models.
"""
id: Optional[int] = Field(default=None, primary_key=True)
created_at: datetime = Field(sa_column=Column(DateTime(timezone=True), default=datetime.utcnow))
updated_at: datetime = Field(sa_column=Column(DateTime(timezone=True),
onupdate=datetime.utcnow, default=datetime.utcnow))
class UUIDModelBase(ModelBase, table=True):
"""
Base class for UUID-based models.
"""
uuid: uuid.UUID = Field(sa_column=Column(psql.UUID(as_uuid=True)), default=uuid.uuid4)
The above errors out with
AttributeError: 'FieldInfo' object has no attribute 'UUID'
I also tried
id: uuid.UUID = Column(psql.UUID(as_uuid=True), default=uuid.uuid4)
TypeError: Boolean value of this clause is not defined
Also
uuid: uuid.UUID = Column(psql.UUID(as_uuid=True), default=uuid.uuid4)
AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'UUID'
and
uuid: uuid.UUID = Field(default_factory=uuid.uuid4, index=True, nullable=False)
AttributeError: 'FieldInfo' object has no attribute 'UUID'
You get the idea. The errors are not helping me, I just need the right syntax.
In this case, I'm not actually looking to use UUID as a primary key. And as you can tell from the imports, I'm using postgreSQL. The database is based on a postgres:12 docker image.