Search code examples
postgresqlpeewee

Peewee. How generate on conflict on constrain for specified column?


I use peewee with postgresql. I try generate query for many entries insertion with resolving insertion conflict for specified column.

models.py

from peewee import *

from datetime import date

from db_init import db


class User(Model):
    username = CharField(constraints=[SQL('CONSTRAINT unique_username UNIQUE')], 
                         max_length=100, unique=True)
    date_create = DateField(default=date.today)

    class Meta:
        table_name = '_users'
        database = db

I run this code

usernames = [f'username{i}' for i in range(5)]
data = [{'username': username} for username in usernames]
q = User.insert_many(data, fields=[User.username])
q2 = q.on_conflict(action='IGNORE', conflict_target=[User.username])

and expect that generate

INSERT INTO "_users" ("username", "date_create") VALUES ('username0', '2021-06-01'), ('username1', '2021-06-01'), ('username2', '2021-06-01'), ('username3', '2021-06-01'), ('username4', '2021-06-01') ON CONFLICT ("username") DO NOTHING RETURNING "_users"."id"

but peewee generate query without specific column in ON CONFLICT statement

INSERT INTO "_users" ("username", "date_create") VALUES ('username0', '2021-06-01'), ('username1', '2021-06-01'), ('username2', '2021-06-01'), ('username3', '2021-06-01'), ('username4', '2021-06-01') ON CONFLICT DO NOTHING RETURNING "_users"."id"

Please, explain what i do wrong?


Solution

  • This is fixed in Peewee github.com/coleifer/peewee/commit/… - previously Peewee did not support conflict target when action was DO NOTHING/IGNORE. This patch allows conflict target to be specified