【发布时间】:2020-03-16 14:28:47
【问题描述】:
我有两个数据库:一个是master,为了测试,我还有另一个数据库master_test
为了从表中检索总价,我在模型中创建了@classmethod。这种方法可以帮助我得到按月和按年过滤的价格总和。这是类方法:
@classmethod
def get_total_book_price(cls, id):
query = Book.query.with_entities(
func.sum(Book.price).label("price")
).filter(
extract('year', Book.created_at) >= datetime.date.today().year,
extract('month', Book.created_at) >= datetime.date.today().month
).filter(
Book.id == id
).all()
return query[0].price
这个查询很好用。但是当我为测试用例运行它时,它显示 master 数据库不存在。它应该找到master_test 数据库而不是master 数据库。
下面是测试代码:
def test_get_total_book_price(self):
id = 1
response = Book.get_total_book_price(id)
if not response:
self.assertEqual(response, False)
self.assertEqual(response, True)
它显示错误:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: database "master"
does not exist
(Background on this error at: http://sqlalche.me/e/e3q8)
----------------------------------------------------------------------
Ran 34 tests in 2.011s
FAILED (errors=1)
ERROR: Job failed: exit code 1
其他一些测试用例与master_test 配合得很好。但是对于这个测试,它为什么要寻找master 数据库?
【问题讨论】:
-
您展示的代码首先如何了解任何数据库?大概这是以某种方式融入
Book。
标签: python python-3.x flask flask-sqlalchemy