Thanks, I used the first method. Follow up question: How do I get the new 
primary key after running `session.commit()`?

On Tuesday, December 19, 2017 at 11:29:34 AM UTC-5, Mike Bayer wrote:
>
> On Tue, Dec 19, 2017 at 3:02 AM, Tom Tanner 
> <dontsende...@gmail.com <javascript:>> wrote: 
> > I'm using SQLAlchemy with the Python library Flask. 
> > 
> > How do I query an object from a database, make a copy of it, and save 
> that 
> > copy to the database? 
> > 
> > Example of querying an object. 
> > someObj = db.session.query(SomeDataTable).filter_by(id=someID).first() 
> > 
> > 
> > I want to save a copy of `someObj` to the table. How do I do this? 
>
> OK so "copy" we will take to mean, a new row in the table, with all 
> the same data, *except* for the primary key, as that has to be 
> different. 
>
> The kind of primary key your object has is important here.   Let's say 
> it's a single integer "id" column that is generated from the database. 
>   You'd do this: 
>
> from sqlalchemy.orm import make_transient 
> make_transient(someObj)   # someObj is no longer in the session 
> del someObj.id   # assume this is the primary key 
> session.add(someObj) 
> session.commit() 
>
>
> if OTOH your object has a natural primary key (one that you set in 
> python), then instead of "del someObj.id" you would assign a new 
> primary key value to be used. 
>
>
> that's it ! 
>
>
>
>  All you do is this: 
>
>
>
>
> > 
> > -- 
> > SQLAlchemy - 
> > The Python SQL Toolkit and Object Relational Mapper 
> > 
> > http://www.sqlalchemy.org/ 
> > 
> > To post example code, please provide an MCVE: Minimal, Complete, and 
> > Verifiable Example. See http://stackoverflow.com/help/mcve for a full 
> > description. 
> > --- 
> > You received this message because you are subscribed to the Google 
> Groups 
> > "sqlalchemy" group. 
> > To unsubscribe from this group and stop receiving emails from it, send 
> an 
> > email to sqlalchemy+...@googlegroups.com <javascript:>. 
> > To post to this group, send email to sqlal...@googlegroups.com 
> <javascript:>. 
> > Visit this group at https://groups.google.com/group/sqlalchemy. 
> > For more options, visit https://groups.google.com/d/optout. 
>

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to