2017-03-15 44 views
0

我在使用SQLAlchemy提交数据库更改时遇到问题,但我找不到原因。SQLAlchemy没有对postgres提交更改

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

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中使用数组类型,但面临同样的确切问题。

+1

您需要的[可变扩展(HTTP://docs.sqlalchemy。组织/ EN /最新/ ORM /扩展/ mutable.html)。 – univerio

+0

[使用postgresql JSON类型与sqlalchemy列表]的可能重复(http://stackoverflow.com/questions/25300447/using-list-on-postgresql-json-type-with-sqlalchemy) – neuront

回答

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')