DarioBB
DarioBB

Reputation: 663

How to insert data with SQlAlchemy declarative way

I can add data to my db this way:

a = Model_tbl_name("3", "da", "3", "eheeee", "", "", "", "", "", "", "", "", func.now(), func.now()) 

db_session.add(a) 
db_session.commit()

But i can't do it this way:

data = Model_tbl_name.insert().values({"title_hr":request.form['title_hr'],"text_hr":request.form['text_hr']})

I tried similar, but no help:

data = db_session.Model_tbl_name.insert().execute({"title_hr":request.form['title_hr'],"text_hr":request.form['text_hr']})

My initial motivation is to pass all form data like JSON, i would like to have it like this to work:

data = db_session.Model_tbl_name.insert().execute(json.loads(new_request_form))

In documentation, it is stated it can be done: http://docs.sqlalchemy.org/en/rel_0_9/core/dml.html?highlight=insert%20values#sqlalchemy.sql.expression.Insert.values

like this:

users.insert().values({"name": "some name"})

But no help, I just can't get it. How can i make it to work, must i provide all JSON data in values() method? How should I write that command to make it work?

Second, how can I grab that error, because, I get no error in Flask, only stops working. I can figure out how to display errors when working with SQLAlchemy declarative way.

P.S. I am using Flask framework, SQLAlchemy, and Python version is 3.4

Upvotes: 5

Views: 7475

Answers (3)

Muayyad Alsadi
Muayyad Alsadi

Reputation: 1593

if you need the insert way (let's say because you want to pass .prefix_with('IGNORE'))

you can do it like this

session.execute(Model_tbl_name.__table__.insert().values(
  col1=val1, col2=val2).prefix_with('IGNORE'))

Upvotes: 2

Alex-Bogdanov
Alex-Bogdanov

Reputation: 2438

it works good with Connection class:

        import sqlalchemy as sa

        conn.execute(
            sa.insert(Model_tbl_name).values(
                {
                    Model_tbl_name.field1: 'value1',
                    Model_tbl_name.field2: 'value2',
                    Model_tbl_name.field3: 'value3', 
                }
            )
        )

Upvotes: 0

Boaz
Boaz

Reputation: 5084

Well, I don't think you can do db_session.Class_name.
This is what you can do with it: http://docs.sqlalchemy.org/en/rel_1_0/orm/session_basics.html

If your problem is the default values, you can define relevant default values in the Model, and then you can construct an object with less fields.

a = Model_tbl_name(title_hr=request.form['title_hr'],
                   text_hr=request.form['text_hr'])

If you still want to pass the dictionary, you can do the following:

dataDict = json.loads(new_request_form)
a = Model_tbl_name(**dataDict)
db_session.add(a) 
db_session.commit()

IMHO - the first method is more readable and reliable (you can check for validity of the params - that they match the object) -> at the end of the day, more secure...

Upvotes: 3

Related Questions