satoru
satoru

Reputation: 33225

How to use type hint with SQLAlchemy models?

Let's we have a model defined as a subclass of the declarative base:

class User(Base):
    name = Column(String)

Later, I define a function that returned a User and specify the returned type as a type hint:

def find_user(name: str) -> User:
    ...
    return user

When I try to use the name field of returned value as a string, the type system complains that it's a Column, not a string. What can I do to add type hint in such cases?

Upvotes: 0

Views: 2882

Answers (2)

Maxim Fomin
Maxim Fomin

Reputation: 47

You can try to use SQLModel that substitutes SQLAlchemy models with its own combination of SQLAlchemy and Pydantic models that are based on regular type annotations (like id: int).

Upvotes: 0

ljmc
ljmc

Reputation: 5264

You could map a dataclass which will have appropriate hints (docs).

That way, you have the type hints from dataclass declaration, and you map to a SQLAlchemy column via the metadata.

from dataclasses import dataclass, field

from sqlalchemy.orm import registry, relationship

mapper_registry = registry()

@mapper_registry.mapped
@dataclass
class User:
    __tablename__ = "user"
    __sa_dataclass_metadata_key__ = "sa"
    id: int = field(init=False, metadata={"sa": Column(Integer, primary_key=True)})
    name: str = field(init=False, metadata={"sa": Column(String, nullable=False)})

Upvotes: 1

Related Questions