Search code examples
postgresqlpeewee

How to upsert based on values from another table?


I'm trying to UPSERT into postgres DB based on values from another table using PeeWee.

**table1**
pk_t1 int
name
city
country
**table2**
pk_t2 int
name
city
country
comments
INSERT INTO table2 (pk_t2, name, city, country) 
SELECT pk_1, name, city, country
FROM   table1
ON     CONFLICT (pk_t2) DO UPDATE  
SET    name = excluded.name, city = excluded.city, country = excluded.country;           

But I'm unable to find a suitable peewee example from documents or SO.


Solution

  • Here you go:

    q = T1.select()
    
    iq = (T2
          .insert_from(q, fields=[T2.id, T2.name, T2.city, T2.country])
          .on_conflict(conflict_target=[T2.id], preserve=[T2.name, T2.city, T2.country]))
    

    Corresponding SQL peewee generates:

    insert into t2 (id, name, city, country)
    select t1.id, t1.name, t1.city, t1.country
    from t1
    on conflict(id) do update set 
      name=excluded.name,
      city=excluded.city,
      country=excluded.country