【问题标题】:SQLAlchemy not committing changes to postgresSQLAlchemy 不提交对 postgres 的更改
【发布时间】:2017-08-06 21:26:27
【问题描述】:

我在使用 SQLAlchemy 提交数据库更改时遇到问题,我无法弄清楚原因。

这里是有问题的数据模型:

class EmailGroup(db.Model):
    __tablename__ = 'email_group'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), unique=True, nullable=False)
    data = db.Column(db.JSON)

def __init__(self, name):
    self.name = name
    self.data = {u'members': []}

def addUser(self, username):
    data = self.data
    if username not in data[u'members']:
        data[u'members'].append(username)
        self.data = data

这是服务器代码:

@app.route('/emailgroup/<groupid>/adduser/<userid>', methods=['POST'])
@jwt_required()
def emailGroupAddUser(groupid, userid):
    emailgroup = EmailGroup.query.filter_by(id=groupid).first()
    if not emailgroup:
        return 'Group with id ' + groupid + ' does not exist.', status.HTTP_400_BAD_REQUEST
    user = User.query.filter_by(id=userid).first()
    if not user:
        return 'User with id ' + userid + ' does not exist.', status.HTTP_400_BAD_REQUEST
    emailgroup.addUser(user.username)
    print emailgroup.dumps() # Is correctly updated here
    db.session.add(emailgroup)
    db.session.commit()
    print emailgroup.dumps() # Changes did not go through!
    return jsonify(emailgroup.dumps())

我也尝试使用db.session.flush() 代替add/commit,这使得两个打印语句打印正确的输出,但实际上仍然没有更新数据库。

编辑:我也尝试在 SQLAlchemy 中使用 Array 类型,但遇到了同样的问题。

【问题讨论】:

标签: python postgresql sqlalchemy


【解决方案1】:

在处理JSON 列时,您可以调用flag_modified 而不是尝试在任意级别的嵌套上使用可变扩展:

from sqlalchemy.orm.attributes import flag_modified

def addUser(self, username):
    data = self.data
    if username not in data[u'members']:
        data[u'members'].append(username)
        flag_modified(self, 'data')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2013-06-05
    • 2019-10-03
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多