如何在Python SQLAlchemy中获取InstrumentedList的计数?

问题描述 投票:0回答:1

我的 SQLAlchemy 模型中有以下惰性关系:

class AuthorModel(db.Model):
    books = db.relationship("BookModel", backref="authors", lazy=True)
    def bookCount(self):
        return self.books.count()    

我想获取作者的书籍数量,但我收到以下错误:

TypeError list.count() takes exactly one argument (0 given)

如有任何建议和见解,我们将不胜感激。

python python-3.x list flask-sqlalchemy
1个回答
0
投票

这是它在 SQLAlchemy 中的实现方式:

class InstrumentedList(List[_T]):
    """An instrumented version of the built-in list."""

因此,您应该能够将其视为一个列表并获得长度:

len(list(self.books))
© www.soinside.com 2019 - 2024. All rights reserved.