Flask-SQLalchemy update a row's information

前端 未结 5 2138
南方客
南方客 2020-12-02 03:59

How can I update a row\'s information?

For example I\'d like to alter the name column of the row that has the id 5.

5条回答
  •  日久生厌
    2020-12-02 04:43

    This does not work if you modify a pickled attribute of the model. Pickled attributes should be replaced in order to trigger updates:

    from flask import Flask
    from flask.ext.sqlalchemy import SQLAlchemy
    from pprint import pprint
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqllite:////tmp/users.db'
    db = SQLAlchemy(app)
    
    
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(80), unique=True)
        data = db.Column(db.PickleType())
    
        def __init__(self, name, data):
            self.name = name
            self.data = data
    
        def __repr__(self):
            return '' % self.username
    
    db.create_all()
    
    # Create a user.
    bob = User('Bob', {})
    db.session.add(bob)
    db.session.commit()
    
    # Retrieve the row by its name.
    bob = User.query.filter_by(name='Bob').first()
    pprint(bob.data)  # {}
    
    # Modifying data is ignored.
    bob.data['foo'] = 123
    db.session.commit()
    bob = User.query.filter_by(name='Bob').first()
    pprint(bob.data)  # {}
    
    # Replacing data is respected.
    bob.data = {'bar': 321}
    db.session.commit()
    bob = User.query.filter_by(name='Bob').first()
    pprint(bob.data)  # {'bar': 321}
    
    # Modifying data is ignored.
    bob.data['moo'] = 789
    db.session.commit()
    bob = User.query.filter_by(name='Bob').first()
    pprint(bob.data)  # {'bar': 321}
    

提交回复
热议问题