简体   繁体   English

如何将 __len__ 添加到 sqlalchemy 声明性元?

[英]How to add __len__ to sqlalchemy declarative meta?

I have added the __len__ method to the User class as shown below:我已将__len__方法添加到User class 中,如下所示:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import func

Base = declarative_base()

class User(Base):
    __tablename__ = "user"
    id = Column(INTEGER(unsigned=True), autoincrement=True, primary_key=True)

    def __len__() -> int:
        try:
            session = Session()
            return session.query(func.count(User.id)).scalar()
        except:
            raise
        finally:
            session.close()

Calling User.__len__() works fine.调用User.__len__()工作正常。 However, calling len(User) yields the following error:但是,调用len(User)会产生以下错误:

TypeError: object of type 'DeclarativeMeta' has no len()

I am not exactly sure how to adjust the class, such that len(User) is recognised as a valid statement.我不确定如何调整 class,以便将len(User)识别为有效语句。

I guess you are trying to find the length of the object of class User not the length of the User class itself?我猜你想找到 class User的 object 的长度而不是User class 本身的长度?

If you do:如果你这样做:

user = User()
len(user)

it will not have the same error它不会有同样的错误

Finally works, needed to call __init__ .最后工作,需要调用__init__

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import func

Base = declarative_base()

class User(Base):
    __tablename__ = "user"
    id = Column(INTEGER(unsigned=True), autoincrement=True, primary_key=True)

    def __init__(self, *args, **kwargs) -> None:
        super(User, self).__init__(*args, **kwargs)

    def __len__(self) -> int:
        try:
            session = Session()
            return session.query(func.count(User.id)).scalar()
        except:
            raise
        finally:
            session.close()

And also instead of calling len(User) , I should have used len(User()) .而且我应该使用len(User())而不是调用len(User) ) 。 (Thanks @Cheukting for this) (感谢@Cheukting)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM