Search code examples
flasksqlalchemyflask-sqlalchemyflask-admin

How to save a record to an alternate model?


My project is in flask-admin using flask-sqlalchemy as the ORM.

Here's my model class:

class history_records(db.Model):
  id = db.Column(db.Integer,primary_key=True)
  table = db.Column(db.String(80))
  field_name = db.Column(db.String(80))
  old_value = db.Column(db.String(80))
  new_value = db.Column(db.Text)
  updated_datetime = db.Column(db.DateTime,default=datetime.utcnow())
  updated_by = db.Column(db.String(80),db.ForeignKey('users.username'))

  def __init__(self,table="",field_name="",updated_datetime=""):
    self.name = table + ' - ' + field_name + ' - ' + updated_datetime

  def __repr__(self):
    return self.name

Then:

class my_view(ModelView):
  #... form configs ...

  def on_model_change(self,form,model,is_created=False):
    #...do some stuff...
    history = history_records() # .get_create_form()

    history.table = model_name
    history.field_name = field_name
    history.old_value = old_value
    history.new_value = new_value

All my other views inherit from my_view and I am specifically trying to write it so I don't have to have a custom on_model_change in each view using the field names for that view.

The piece I am missing is how to get my application to save the history_records record that the on_model_change method creates to the database (postgres). An instance of the class is instantiated and it has the requisite information, so how do I save the instance to the database?

I have been referencing these pages without success:

Any help would be greatly appreciated.


Solution

  • To save the history instance you need to add it to the view's session e.g.

    def on_model_change(self,form,model,is_created=False):
        #...do some stuff...
        history = history_records() # .get_create_form()
    
        history.table = model_name
        history.field_name = field_name
        history.old_value = old_value
        history.new_value = new_value
        self.session.add(history)