2

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.

Community
  • 1
  • 1
Alison S
  • 1,759
  • 1
  • 14
  • 28

1 Answers1

3

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)
pjcunningham
  • 7,676
  • 1
  • 36
  • 49
  • Thank you for your help @pjcunningham. I added the line `self.session.add(history)` but that resulted in getting this error: ProgrammingError: – Alison S Mar 04 '16 at 19:29
  • Based on this: http://stackoverflow.com/a/13089951/1807668 I cast the variables `model_name`, `field_name`, `old_value`, and `new_value` to `str()` and then it worked. – Alison S Mar 04 '16 at 19:42