grichiec
grichiec

Reputation: 33

Flask-Admin: Inserting data in two tables at once

This is the first project that I've used flask/flask-admin on. We have an API, created using flask and are now working on an admin interface to it. One of the requirements is upon the creation of a record in TableA, a number of related records need to be created in TableB which includes the ROW_ID of the new TableA entry.

I've created a form for the entry of data in to TableA (which works fine), but don't know how to go about automatically adding data to TableB. Is the new (TableA) ROW_ID returned once the data has been committed to the table? Is there a better way to do this?

Any thoughts?

Upvotes: 3

Views: 2074

Answers (1)

Rachel Sanders
Rachel Sanders

Reputation: 5874

The docs don't have a great example of it, but you can override all of the CRUD operations for models, including creation. You can handle creating and saving the model yourself, at which you have the primary key, and can make any other queries and create any other models you need.

I cobbled this together out of our code, so hopefully it's complete enough. Let me know if any of it's confusing, or it doesn't answer your question.

http://flask-admin.readthedocs.org/en/latest/quickstart/#model-views

from your_models import Employee, Manatee

from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView


class EmployeeAdminView(ModelView):

  # this is called when a model is created
  def create_model(self, form):
    person = Employee() # create new Employee
    form.populate_obj(person)  # use WTForms to populate the model

    # create a new manatee for this new employee
    # everybody needs a manatee for business purposes
    # this assumes there's a sqlalchemy relationship() between the two models

    manatee = Manatee() 
    manatee.name = "Janet"

    person.manatee = manatee 

    self.session.add(person)
    self.session.commit()

    # at this point person.id should be available, so you can use that here
    # to make any other queries you need to

    return True

admin = Admin(app)
admin.add_view(EmployeeAdminView(Employee, db.session)) 

Upvotes: 2

Related Questions