数据库
首页 > 数据库> > python-AttributeError:“ NoneType”对象在Flask,SQLAlchemy中没有属性“ time_recorded”

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

作者:互联网

我有一个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字段是:

id = db.Column(db.String,default=lambda: str(uuid4().hex), primary_key=True)

我尝试使用filter而不是filter_by,但它不起作用.当我删除filter_by(id = lastqnid)时,它可以工作.不运行查询的原因可能是什么?

正在查询的交易表是

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)

解决方法:

您似乎遇到的问题是在使用结果前不检查是否找到了任何东西

@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()

标签:python,sqlalchemy,flask,flask-sqlalchemy
来源: https://codeday.me/bug/20191013/1909703.html