SqlAlchemy更新不与Sqlite一起使用 [英] SqlAlchemy update not working with Sqlite

查看:150
本文介绍了SqlAlchemy更新不与Sqlite一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循这个问题中的(两个)例子:SQLAlchemy:一个更好的方式来更新声明?



我发现在Ubuntu Linux上使用sqlite和flask-sqlalchemy时,模型更新不会发生。最简单的例子不适用于我:

 类任务:
id = db.Column(db。 Integer,primary_key = True)
name = db.Column(db.String(32),unique = True)
desc = db.Column(db.String(255),unique = False)
state = db.Column(db.Boolean)

#...

@ app.route(/ task /< int:id> / update ,方法= [POST])
def toggle_state(id):
db.session.query(Task).get(id).update({state:True})
log.info(state is now:+ str(Task.query.get(id).state))
#printsstate is now:False


第一次使用flask / sqlalchemy,所以我想我错过了一些明显的东西。

解决方案

所以我尝试了几个不同的东西。这是什么不工作,什么最终没有工作:

没有工作:

pre > #这将抛出一个异常,AttributeError:任务'对象没有任何属性'更新'
db.session.query(Task).get(id).update({状态:状态})
db.session.commit()

#这是链接的SO线程中的示例:
#不做任何事
db.session .query(Task).filter_by(id = id).update({state:state})

#this也没有做任何事
task = Task.query.filter_by(id = id)
task.state = state
db.session.commit()

#不是
task = Task.query.get(id)
task.state = state
db.session.commit()



  #ok这样做:
db.session.query(Task).filter_by(id = id).update ({state:state})
db.session.commit()

#也是这样的:
task = db.session.query(Task).get id)
task.state =状态
db.session.commit()


I followed the (two) examples in this question: SQLAlchemy: a better way for update with declarative?

And I'm finding that a model update does not happen when using sqlite with flask-sqlalchemy on Ubuntu Linux. The very simplest example doesn't work for me:

class Task:
    id= db.Column(db.Integer, primary_key=True)
    name= db.Column(db.String(32), unique=True)
    desc= db.Column(db.String(255), unique=False)
    state= db.Column(db.Boolean)

    # ...

@app.route("/task/<int:id>/update",methods=["POST"])
def toggle_state(id):
    db.session.query(Task).get(id).update({"state":True})
    log.info("state is now: " + str(Task.query.get(id).state))
    # prints "state is now: False"

First time using flask/sqlalchemy, so I assume I'm missing something obvious.

解决方案

So I tried several different things. Here's what didn't work, and what finally did work:

Didn't work:

# this will throw an exception, "AttributeError: 'Task' object has no attribute 'update'"
db.session.query(Task).get(id).update({"state":state})
db.session.commit()

# this was the example in the linked SO thread:
# does nothing
db.session.query(Task).filter_by(id=id).update({"state":state})

#this also does nothing
task = Task.query.filter_by(id=id)
task.state = state
db.session.commit()

#not this either
task = Task.query.get(id)
task.state = state
db.session.commit()

Did work:

#ok this works:
db.session.query(Task).filter_by(id=id).update({"state":state})
db.session.commit()

#and also this:
task = db.session.query(Task).get(id)
task.state = state
db.session.commit()

这篇关于SqlAlchemy更新不与Sqlite一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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