I am having trouble committing database changes using SQLAlchemy and I cannot figure out why.
Here is the data model in question:
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
Here is the server code:
@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())
I have also tried using db.session.flush()
instead of add/commit
, which makes the two print statements print the correct outputs, but does not actually update the database still.
EDIT: I also tried using the Array type in SQLAlchemy but faced the same exact issue.
When dealing with JSON
columns, you can call flag_modified
rather than try to use the mutable extensions on arbitrary levels of nesting:
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.