Possible to bulk update with different values?

1,521 views
Skip to first unread message

Brian Clark

unread,
Dec 23, 2016, 3:11:12 PM12/23/16
to sqlalchemy
Is there an update equivalent of this insert statement?

inserts = [{"name": "jon", "age": 20"}, {"name": "ashley", "age": 22"}]
session.execute(
    People.__table__.insert().values(
        inserts
    )
)

I have this right now but it's still slower than I'd like because it's using executemany, hoping to have it be one big query

updated_people = [{"b_id": 1, "b_name": "jon", "b_age": 21"}, {"b_id": 2, "b_name": "ashley", "b_age": 25"}]
stmt = People.__table__.update().\
                  where(People.id == bindparam('b_id')).\
                  values(name=bindparam('b_name'), age=bindparam('b_age'))
session.execute(stmt, updated_people)

Thanks!

Brian Clark

unread,
Dec 23, 2016, 3:21:09 PM12/23/16
to sqlalchemy

mike bayer

unread,
Dec 23, 2016, 6:32:51 PM12/23/16
to sqlal...@googlegroups.com

Here's Postgresql's UPDATE syntax:

https://www.postgresql.org/docs/9.5/static/sql-update.html

as you can see the WHERE clause has only one option, so it's one row at
a time.
> --
> 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
> <mailto:sqlalchemy+...@googlegroups.com>.
> To post to this group, send email to sqlal...@googlegroups.com
> <mailto:sqlal...@googlegroups.com>.
> Visit this group at https://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/d/optout.

mike bayer

unread,
Dec 23, 2016, 6:39:15 PM12/23/16
to sqlal...@googlegroups.com
that pattern is not supported in SQLAlchemy Core.

Jonathan Vanasco

unread,
Dec 23, 2016, 10:16:21 PM12/23/16
to sqlalchemy

If you really need to do something like that though, you can always string together raw sql + bindparams, and pipe it all through an `execute` into the dbcursor.

Brian Clark

unread,
Dec 24, 2016, 2:38:40 AM12/24/16
to sqlalchemy
Got it, thanks!


On Friday, December 23, 2016 at 12:11:12 PM UTC-8, Brian Clark wrote:
Reply all
Reply to author
Forward
0 new messages