Dear all,
I am currently working on implementing UUID as primary keys in my database.
I have come across an issue that I cannot find an explanation for: using the `sqlalchemy.Uuid` type in declarative mapping yields different results at initialization. I sometimes get the following error:
"The type provided inside the 'id' attribute Mapped annotation is the SQLAlchemy type <class 'sqlalchemy.sql.sqltypes.Uuid'>. Expected a Python type instead"
I have a Caregiver table, for which id is a PostgreSQL UUID, and a Match Event table holding 2 fields which use the Caregiver id as foreign key. Those 2 fields are PostgreSQL UUID as well.
If my classes definitions are as follow, the initialization runs smoothly, as well as inserts in the Match Event table:
from sqlalchemy import (
ForeignKey,
Uuid,
)
from sqlalchemy.orm import (
Mapped,
mapped_column,
relationship,
)
class MatchEventOrm(Base):
__tablename__ = "match_event"
id: Mapped[int] = mapped_column(primary_key=True)
subject_caregiver_id: Mapped[Uuid] = mapped_column(
)
object_caregiver_id: Mapped[Uuid] = mapped_column(
)
subject_caregiver: Mapped["CaregiverOrm"] = relationship(
back_populates="match_event_subject_of",
foreign_keys=[subject_caregiver_id],
)
object_caregiver: Mapped["CaregiverOrm"] = relationship(
back_populates="match_event_object_of",
foreign_keys=[object_caregiver_id],
)
class CaregiverOrm(Base):
__tablename__ = "caregiver"
id: Mapped[str] = mapped_column(primary_key=True)
uid: Mapped[str]
user_email: Mapped[str]
...
However, if I change to the following:
from sqlalchemy import (
ForeignKey,
Uuid,
)
from sqlalchemy.orm import (
Mapped,
mapped_column,
relationship,
)
class MatchEventOrm(Base):
__tablename__ = "match_event"
id: Mapped[int] = mapped_column(primary_key=True)
subject_caregiver_id: Mapped[Uuid] = mapped_column(
)
object_caregiver_id: Mapped[Uuid] = mapped_column(
)
subject_caregiver: Mapped["CaregiverOrm"] = relationship(
back_populates="match_event_subject_of",
foreign_keys=[subject_caregiver_id],
)
object_caregiver: Mapped["CaregiverOrm"] = relationship(
back_populates="match_event_object_of",
foreign_keys=[object_caregiver_id],
)
class CaregiverOrm(Base):
__tablename__ = "caregiver"
id: Mapped[Uuid] = mapped_column(primary_key=True)
uid: Mapped[str]
user_email: Mapped[str]
...
I get the aforementioned error message.
I may be using type annotations wrong, any insight on what I am doing wrong would be welcome.
Thanks a lot for your support.
Regards,
Pierre