Gino: How to chain e.g. on_conflict_do_nothing() to Model.create()?

Created on 8 Oct 2019  路  2Comments  路  Source: python-gino/gino

  • GINO version: 0.8.3
  • Python version: 3.7.3
  • asyncpg version: 0.18.3
  • aiocontextvars version: 0.2.2
  • PostgreSQL version: 11.5

Description

First of all, Gino seems awesome. Thanks for your hard work :)

I'm trying to understand how can I use things like on_conflict_do_nothing() (https://docs.sqlalchemy.org/en/13/dialects/postgresql.html#insert-on-conflict-upsert)
when using Gino ORM. Full example below, but basically this is what I'm trying to achieve:

await User.create(id='1', name='jack', fullname='Jack Jones')  # succeeds
await User.create(id='1', name='jack', fullname='Jack Jones').on_conflict_do_nothing()  # raises exception

How should things like these be approached when using Gino?
Thank you for your time!

What I Did

from gino import Gino

db = Gino()


class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    fullname = db.Column(db.String)


async def main():
    async with db.with_bind('postgresql://localhost/gino'):
        await db.gino.create_all()
        await User.create(id='1', name='jack', fullname='Jack Jones')

        # how to do something similar to this:
        await User.create(id='1', name='jack', fullname='Jack Jones').on_conflict_do_nothing()
question

Most helpful comment

Thanks for the question! Please see example below:

        from sqlalchemy.dialects.postgresql import insert

        stmt = insert(User).values(id=1, name="jack", fullname="Jack Jones")
        stmt = stmt.on_conflict_do_update(
            index_elements=[User.id], set_=dict(id=stmt.excluded.id)
        ).returning(*User)
        user = await stmt.gino.model(User).first()
        # INSERT INTO users (id, name, fullname) VALUES ($1, $2, $3)
        # ON CONFLICT (id) DO UPDATE SET id = excluded.id
        # RETURNING users.id, users.name, users.fullname

All 2 comments

Thanks for the question! Please see example below:

        from sqlalchemy.dialects.postgresql import insert

        stmt = insert(User).values(id=1, name="jack", fullname="Jack Jones")
        stmt = stmt.on_conflict_do_update(
            index_elements=[User.id], set_=dict(id=stmt.excluded.id)
        ).returning(*User)
        user = await stmt.gino.model(User).first()
        # INSERT INTO users (id, name, fullname) VALUES ($1, $2, $3)
        # ON CONFLICT (id) DO UPDATE SET id = excluded.id
        # RETURNING users.id, users.name, users.fullname

Great, thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

quantum13 picture quantum13  路  6Comments

paulin-mipt picture paulin-mipt  路  4Comments

aprilmay picture aprilmay  路  3Comments

AmatanHead picture AmatanHead  路  5Comments

willyhakim picture willyhakim  路  4Comments