如何使用query.all()计算sqlalchemy数据库中ID的数量?

时间:2019-11-08 13:33:06

标签: python flask sqlalchemy

class Artist(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    artist_name = db.Column(db.String(200))
    albums = db.relationship('Album',
                            backref='artist',
                            lazy=True)

    def __repr__(self):
        return "<Artist '{}'>".format(self.artist_name)

这是测试班

def test_artists_count(self):
        c = Artist.query.all()
        self.assertEqual(2, c)

这是我遇到的错误

Traceback (most recent call last):enter code here
  File "/projects/challenge/myflaskproj/tests/test_models.py", line 65, in test_artists_count

self.assertEqual(2, c)

AssertionError: 2 != [<Artist 'Artist1'>, <Artist 'Artist2'>]

1 个答案:

答案 0 :(得分:0)

您可以通过检查查询结果的长度来检查查询结果的行数或行数

您唯一需要更改的行是:

self.assertEqual(2, len(c))