On Aug 5, 2011, at 2:00 PM, Stefano Fontanelli wrote: > Il 05/08/11 19.29, Mark Erbaugh ha scritto: >> In a declaratively created table, is there an automatic way to get a new >> instance of the class object to be populated with values specified in a >> 'default' clause? >> >> i.e. >> >> class MyTable(Base): >> __tablename__ = 'table' >> name = Column(String, default='new name') >> ... >> >> >> newRow = MyTable() >> >> is there a way to have newRow.name automatically have the value 'new name' >> before it is committed to the database? The best I've been able to come up >> with so far is to use a 'CONSTANT' in the default clause and use that same >> CONSTANT to initialize the field in the class' __init__, but this doesn't >> seem very DRY. >> >> Or, maybe is this the wrong question? Maybe I'm trying to do things the >> wrong way. I'm trying to use mostly the same code add a new row or edit an >> existing row. If the user is adding a record, I create a new instance of >> the class and use the add/edit screen to edit the data. If the user is >> editing an existing row, I retrieve the row, then use the add/edit screen >> with it. >> >> Thanks, >> Mark >> > > Hi Mark, > to fill with defaults you can do: > > newRow = MyTable() > session.add(newRow) > session.flush() > print newRow.name > > 'print newRow.name' will display 'new name' > > To use the same code for create/update I suggest you to use session.merge: > http://www.sqlalchemy.org/docs/orm/session.html#merging
Stefano, Thanks for the reply. The problem I see with this approach is that I think it actually commits the new row to the database. In the app, it's possible that the user could decide to cancel before inserting the new row. Of course, I could back out the addition, but it seems like it would be better to not insert in the first place. Mark -- 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.
