How to use PostgreSQL's "INSERT...ON CONFLICT" (UPSERT) feature with flask_sqlalchemy?
It turns out you can execute a lower-level statement on the db.session
. So a solution looks something like this:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import insert as pg_insert
app = Flask(__name__)
db = SQLAlchemy(app)
class MyTable(db.Model):
id = db.Column(UUID, primary_key=True)
data = db.Column(db.String)
def __init__(self, _id, *args, **kwargs):
self.id = _id
self.data = kwargs['data']
def as_dict(self):
return {'id': self.id, 'data': self.data}
def props_dict(self):
d = self.as_dict()
d.pop('id')
return d
relation = MyTable(id=1, data='foo')
statement = pg_insert(MyTable)\.
values(**relation.as_dict()).\
on_conflict_do_update(constraint='id',
set_=relation.props_dict())
db.session.execute(statement)
db.session.commit()
The as_dict()
and props_dict()
methods in my model class allow me to use the constructor to filter out unwanted properties from the incoming HTTP request.