Statischer Typ für "jede SQLALCHEMEY -ORM -Klasse mit einem Ganzzahlfeld mit dem Namen" ID "" "
Posted: 18 Aug 2025, 03:16
Wie kann ich einer Funktion einen statischen Typ geben, der "eine SQLALCHEMY -ORM -Klasse mit einem Ganzzahlfeld mit dem Namen 'ID'" akzeptieren sollte? Ich musste auf ID zurückgreifen: Jeder , aber ich hoffe immer noch, dass ich es besser machen kann. AM Verwenden Sie Python 3.12.3 und Sqlalchemy 2.0.41.
Code: Select all
from typing import Any, Protocol, TypeVar
import sqlalchemy as sql
from sqlalchemy import orm
class HasIntId(Protocol):
# id: int # Argument 1 to "where" of "Select" has incompatible type "bool" ... [arg-type]
# id: orm.Mapped[int] # Value of type variable "T" of "f" cannot be "Foo" [type-var]
# id: orm.attributes.InstrumentedAttribute[int] # Value of type variable "T" of "f" cannot be "Foo" [type-var]
id: Any
T = TypeVar('T', bound=HasIntId)
def f(model: type[T]) -> sql.Select[tuple[T]]:
return sql.select(model).where(model.id > 42).order_by(model.id.desc())
class Base(orm.DeclarativeBase):
pass
class Foo(Base):
__tablename__ = 'foos'
id: orm.Mapped[int] = orm.mapped_column(primary_key=True)
print(f(Foo))