【问题标题】:AttributeError: 'NoneType' object has no attribute 'time_recorded' in Flask, SQLAlchemyAttributeError:“NoneType”对象在 Flask、SQLAlchemy 中没有属性“time_recorded”
【发布时间】:2018-06-28 07:37:10
【问题描述】:

我有一个 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)

【问题讨论】:

  • 您正在展示导致错误的原因,但我们没有看到与错误相关的代码。什么是time_recorded,它在哪里使用?
  • 如果您在执行result.time_recorded 之类的操作而不检查您是否真的找到任何东西,例如if result == None,它很可能会产生此错误。不过,我只是根据您提供的信息假设...
  • 添加了我正在查询的表
  • 请找到产生错误的行。
  • 错误来自 new_entries = Trades.query.filter(Trades.time_recorded > result.time_recorded).all()

标签: python flask sqlalchemy flask-sqlalchemy


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答。但是正在查询我确定存在于数据库中的记录(我什至检查了数据库并且它在那里)但查询由于某种原因无法正常工作
  • 那么我认为lastqnid 有问题。是否添加了 print 语句来检查它是什么?
  • 是的,它是 uuid4().hex 的输出。实际上,当我取 lastqnid 的值并手动将其放入查询中时,它会按预期工作。
  • 那么输出是什么?你 100% 肯定它是一个字符串吗? type(lastqnid) 说什么?
  • 还有,print(request.url)的输出是什么?
猜你喜欢
  • 2021-05-03
  • 1970-01-01
  • 2014-12-29
  • 2020-06-25
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 2020-07-08
相关资源
最近更新 更多