AttributeError:"NoneType"对象在Flask,SQLAlchemy中没有属性"time_recorded" [英] AttributeError: 'NoneType' object has no attribute 'time_recorded' in Flask, SQLAlchemy

查看:164
本文介绍了AttributeError:"NoneType"对象在Flask,SQLAlchemy中没有属性"time_recorded"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an api endpoint that passes a variable which is used to make a call in the database. For some reason it cannot run the query yet the syntax is correct. My code is below.

@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)时,它可以工作.不运行查询的原因可能是什么?

I have tried filter instead of filter_by and it does not work. When I remove the filter_by(id=lastqnid) it works. What could be the reason it is not running the query?

正在查询的交易表是

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)

推荐答案

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

The issue you seem to be having is not checking if you found anything before using your result

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

这篇关于AttributeError:"NoneType"对象在Flask,SQLAlchemy中没有属性"time_recorded"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆