Very basic scenario that I've been struggling with.  I have a table
called "Entries" in Postgresql with a primary key of type Serial call
"id".  I'm using ORM reflection to map my classes to underlying
tables.  I'm then populating my Entry instance and submitting it for
Insert via session.merge, session.flush, session.commit in that
order.  When I supply a value to Entry.id, it overrides the default
sequence.  When I don't, I get a primary key error.  My goal is create
a new entry record but insert with the generated ID.  Please
help...code below.


-------------------------------------------------------------
#dt_weblog is the data tier for this weblog application
#dt_weblog leverages the SQLAlchemy (0.7.2)  ORM mapper module to
create
#a mapping between the Postgresql tables and their associated Python
Classes
#The Weblog database and tables must be created prior to launch of
this module

from sqlalchemy import *
from sqlalchemy.orm import *

#Creates a Dialect for Postgresql and a Pool object which will be
leveraged by our Session
db = create_engine('postgresql://postgres:genericpassword@localhost:
5432/WebLog', echo=True)

#Create a configured session class.  Will use session instances later
for database communication
Session = sessionmaker(bind=db, autoflush=False, autocommit=False,
expire_on_commit=True)

#Reflect database tables metadata into a variable so that schemas do
not have to be
#explicitly defined in code
metadata = MetaData(db)

#Create table objects whose attributes are based on 'metadata'
variable
users_table = Table('users', metadata, autoload=True)
entries_table = Table('entries', metadata, autoload=True)

#Create classes which whose attributes will be automatically
configured by the mapper based on
#table object attributes
class User(object):
    pass
class Entry(object):
    pass

#Create mapping between tables and associated classes
usermapper = mapper(User, users_table,
primary_key=[users_table.c.username])
entrymapper = mapper(Entry, entries_table,
primary_key=[entries_table.c.id])

>>> s= Session()
>>> e.id
>>> e.id = 0
>>> session.flush()
>>> e.header = 'test'
>>> e.username = 'dfreedman'
>>> e.text = 'test'
>>> s.merge(e)
>>> s.flush()
>>>s.commit()





--------------------------------------------------------------------------------------

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to