Statischer Typ für "jede SQLALCHEMEY -ORM -Klasse mit einem Ganzzahlfeld mit dem Namen" ID "" "

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Statischer Typ für "jede SQLALCHEMEY -ORM -Klasse mit einem Ganzzahlfeld mit dem Namen" ID "" "

by Anonymous » 17 Aug 2025, 11:41

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. class = "Lang-Py PrettyPrint-Override">

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))

Top