关于count()的flask_sqlalchemy TypeError

时间:2019-10-07 19:12:25

标签: python flask sqlalchemy flask-sqlalchemy

在chinook.sqlite数据库中,以下两个表相关。

  

艺术家

  • ArtistId(PK)
  • 名称
  

相册

  • AlbumId(PK)
  • 标题
  • Artistid(FK))

我正在得到反映的数据库元数据

boolean isRightTriangle(int a, int b, int c) {
  if(a>0 && b>0 && c>0){
    if((Math.sqrt((double)a)+Math.sqrt((double)b))==Math.sqrt((double)c)){
      return true;
    }
    else{
      if((Math.sqrt((double)b)+Math.sqrt((double)c))==Math.sqrt((double)a)){
        return true;
      }
      else{
        if((Math.sqrt(c)+Math.sqrt(b))==Math.sqrt(a)){
          return true;
        }
        else{
          return false;
        }
      }
    }
    }
  else{
    return false;
  }
}

在我的模型中。py

app = Flask(__name__, instance_relative_config=True)
db = SQLAlchemy()
db.app = app
db.init_app(app)
db.Model.metadata.reflect(db.engine)

在视图中,

  

{{artist.album.count()}}

给出错误, TypeError:count()仅接受一个参数(给定0)

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

尚未建立ORM关系configured to be dynamic,因此您呼叫Query.count()而不是list.count()。使用len()

{{ len(artist.albums) }}

您的模型定义还定义了额外的关系属性。代替backref(这是在另一端创建新的关系属性的简写),而是使用back_populates将两边链接在一起:

class Album(db.Model):
    __table__ = db.Model.metadata.tables['albums']
    artist = db.relationship('Artist', back_populates = 'albums')

class Artist(db.Model):
    __table__ = db.Model.metadata.tables['artists']
    albums = db.relationship('Album', back_populates = 'artist')