Ryan Skene
Ryan Skene

Reputation: 924

dynamically insert rows to table flask sqlalchemy

I want to insert new rows to an sql table dynamically in SQLAlchemy.

I basically want to do this, but instead of doing it with an UPDATE, I want to do it with an INSERT.

I am using Flask and WTForms.

Right now, I have to add a new user doing this:

if form.validate_on_submit():
    contact_info = UserContactInfo(street_number=form.street_number.data,
                                   street_address = form.street_address.data,
                                   unit_number = form.unit_number.data
                                  )
    db.session.add(contact_info)
    db.session.commit()

I would be able to add new attributes to UserContactInfo alot easier if I could iterate through the Inserts.

I have tried to do it this way, but no change is made to the database.

form = ContactInfoForm()
contact_info = UserContactInfo()

if form.validate_on_submit():
    table_obj_members = get_attributes(UserContactInfo())
        for aa in table_obj_members:
             form_data = getattr(form, aa).data
             setattr(contact_info, aa, form_data)

 db.session.commit()

I have seen a couple discussions around this and instantiating the whole Class and not the object attribute, but I can't seem to make this apply to this problem.

Thanks for any help.

Upvotes: 2

Views: 3496

Answers (1)

leovp
leovp

Reputation: 4768

In your second example you forgot to add modified object to the session before commiting.
There is a function in WTForms that does exactly what you describe: populate_obj() [1].

Example:

if form.validate_on_submit():
    contact_info = UserContactInfo()
    form.populate_obj(contact_info)

    db.session.add(contact_info)
    db.session.commit()

Upvotes: 2

Related Questions