AttributeError:“NoneType”对象在Flask、SQLAlchemy中没有属性“time_recorded”

2024-06-09 19:52:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个api端点,它传递一个用于在数据库中进行调用的变量。由于某些原因,它无法运行查询,但语法是正确的。我的代码在下面。在

@app.route('/api/update/<lastqnid>')
def check_new_entries(lastqnid):
    result = Trades.query.filter_by(id=lastqnid).first()
    new_entries = Trades.query.filter(Trades.time_recorded > result.time_recorded).all()

id字段为:

^{pr2}$

我尝试了filter而不是filter_by,但它不起作用。当我删除filter_by(id=lastqnid)时,它就起作用了。它没有运行查询的原因是什么?在

从中查询的trades表是

class Trades(db.Model):
    id = db.Column(db.String,default=lambda: str(uuid4().hex), primary_key=True)
    amount = db.Column(db.Integer, unique=False)
    time_recorded = db.Column(db.DateTime, unique=False)

Tags: apiidnewdbbytime原因column
1条回答
网友
1楼 · 发布于 2024-06-09 19:52:40

你似乎遇到的问题是在使用结果之前不检查是否发现了任何东西

@app.route('/api/update/<lastqnid>')
def check_new_entries(lastqnid):
    result = Trades.query.filter_by(id=lastqnid).first()
    # Here result may very well be None, so we can make an escape here
    if result == None:
        # You may not want to do exactly this, but this is an example
        print("No Trades found with id=%s" % lastqnid)
        return redirect(request.referrer)
    new_entries = Trades.query.filter(Trades.time_recorded > result.time_recorded).all()

相关问题 更多 >