SQLAlchemy does not set primary key from auto-increment after commit

I am using SQLAlchemy

postgresql to connect to database. I have determined that my primary key columns in postgresql are of type serial

ie auto-increment integer and have tagged them in my model SQLAlchemy

with primary_key=true

.

On session commit, the SQLAlchemy

model is saved to the db and I see the primary key set in the database, but the property id

on my model object is SQLAlchemy

always set None

i.e. it doesn't pick up the autoincrement value. I'm not sure what I did wrong.

I checked existing SO questions but couldn't find an answer:

My code is below:

Create a table in postgres:

CREATE TABLE my_model
(
    id serial NOT NULL,
    type text,
    user_id integer,

    CONSTRAINT pk_network_task PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);

      

Configure SQLAlchemy and Model:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

engine = create_engine(db_url, convert_unicode=True, echo=True)
session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

class MyModel(Base):
    __tablename__ = 'my_model'

    id = sa.Column(sa.Integer, primary_key=True)
    user_id = sa.Column(sa.Integer)
    type = sa.Column(sa.String)

      

Try and save the model:

my_model = MyModel()
user_id = 1
type = "A type"
session.merge(my_model)
session.commit()
my_model.id #Always None, don't know why

      

my_model.id

still None

after commit. I also try to call close

in session, but that didn't work either.

+3


source to share


1 answer


It turns out that I did not understand the difference between

session.merge(my_model)

      

and

session.add(my_model)

      



session.merge(my_model)

(which I used) does not add the object given to it in the session. Instead, it returns a new object, that is, the merged model that was added to the session. If you are referencing this new object, all is well.

my_model = session.merge(my_model)

      

add

on the other hand adds the object provided to it in the session.

+7


source







All Articles