dropbox / sqlalchemy-stubs

Mypy plugin and stubs for SQLAlchemy
Apache License 2.0
570 stars 101 forks source link

Missing imports and arguments when using sqlalchemy.orm.DeclarativeBase #257

Open LordWolfenstein opened 1 year ago

LordWolfenstein commented 1 year ago

When I create a database following this guide: https://docs.sqlalchemy.org/en/20/orm/declarative_styles.html Mypy says imports are missing and missing argument. The code itself works but I get errors with mypy. I am using Python 3.9

My file:

from datetime import datetime
from typing import Optional

from sqlalchemy import ForeignKey, create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, scoped_session, sessionmaker

from ..settings import DATABASE

class Base(DeclarativeBase):
    pass

class Parent(Base):
    __tablename__ = "parent_table"
    id: Mapped[int] = mapped_column(primary_key=True)
    children: Mapped[list["Child"]] = relationship(back_populates="parent")

class Child(Base):
    __tablename__ = "child_table"
    id: Mapped[int] = mapped_column(primary_key=True)
    parent_id: Mapped[int] = mapped_column(ForeignKey("parent_table.id"))
    parent: Mapped["Parent"] = relationship(back_populates="children")

My errors:

db.py:5: error: Module "sqlalchemy.orm" has no attribute "DeclarativeBase"
db.py:5: error: Module "sqlalchemy.orm" has no attribute "Mapped"; maybe "Mapper"?
db.py:5: error: Module "sqlalchemy.orm" has no attribute "mapped_column"
db.py:17: error: Missing positional argument "argument" in call to "RelationshipProperty"
db.py:24: error: Missing positional argument "argument" in call to "RelationshipProperty"
Kakadus commented 12 months ago

As a workaround, you can import those from sqlalchemy.orm.decl_api instead

BakinSergey commented 10 months ago

in my case, it was just necessary to delete stubs: pip uninstall sqlalchemy-stubs pip uninstall sqlalchemy2-stubs

markalanboyd commented 9 months ago

in my case, it was just necessary to delete stubs: pip uninstall sqlalchemy-stubs pip uninstall sqlalchemy2-stubs

Thank you! This solved it for me as well.