简体   繁体   中英

How to set hash of a column in another column in flask-admin?

I want to save hash of name to hash_name column Also I use Flask-Admin to manage my data.

class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.Unicode, unique=True, nullable=False)
    hash_name = db.Column(db.Unicode, unique=True)

admin.add_view(ModelView(User, db.session))

Also I set default with uuid package for hash_name but this page in result had a problem .my uuid never changed . I refreshed but not changed

If you only use flask-admin's SQLAlchemy ModelViews for editing, then it's possible to do following:

class UserView(sqla.ModelView):
    # Hide `hash_name` in list and form views
    column_exclude_list = ('hash_name',)
    form_excluded_columns = ('hash_name',)

    # Generate new hash on `name` change
    def on_model_change(self, form, model, is_created):
        if len(model.name):
            model.hash_name = generate_hash_name(model.name)

Otherwise use @mehdy's event approach.

I think you can use sqlalchemy's even listeners to manipulate your object before committing it to the database:

from sqlalchemy import event
...
@event.listens_for(User, "before_commit")
def gen_default(mapper, connection, instance):
    instance.hash_name = hash_function(instance.name)

so before each commit it will be invoked and updates the hash_name attribute with the proper hash on name

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM