I have a table with primary uuid key, unique article and some other params.
My model:
class Product(Base):
__tablename__ = "products"
idf: Mapped[str] = mapped_column(primary_key=True, unique=True)
name: Mapped[str] = mapped_column(nullable=False)
article: Mapped[str] = mapped_column(nullable=False, unique=True)
category: Mapped[str] = mapped_column(default="")
description: Mapped[str] = mapped_column(default="")
Firstly, I’m inserting a large list of objects with the function below:
async def import(self, db: AsyncSession, objects):
await db.run_sync(lambda session: session.bulk_save_objects(objects))
await db.commit()
return {"status": "Import has been finished"}
When I use this function with similar list (for ex. one dict has a different name), I need to check unique article existing in postgres table and if it does all properties except primary uuid key and unique article should be updated. Any ideas how to do it?
2
Answers
I think you want to do a upsert use:
https://docs.sqlalchemy.org/en/20/dialects/postgresql.html#postgresql-insert-on-conflict
bulk_save_objects is deprecated: https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.bulk_save_objects
So you do:
You can catch Integrity Error, if unique attribute is already used:
Also see this good explanation for catching Integrity Errors:
https://stackoverflow.com/a/25877950/21437866