def get_upsert_sql(self, rows, unique_fields, update_fields):
        ModelClass = self.tables[0].model
        all_fields = ModelClass._meta.fields
        pk_name = ModelClass._meta.pk.name
        all_field_names = [field.name for field in all_fields if field.name != pk_name]
        all_field_names_sql = ', '.join(all_field_names)
        unique_field_names_sql = ', '.join(unique_fields)
        update_fields_sql = ', '.join(['{0} = EXCLUDED.{0}'.format(field_name) for field_name in update_fields])

        row_values = []
        sql_args = []

        for row in rows:
            placeholders = []
            for field_name in all_field_names:
                sql_args.append(getattr(row, field_name))
                placeholders.append('%s')
            row_values.append('({0})'.format(', '.join(placeholders)))
        row_values_sql = ', '.join(row_values)

        self.sql = 'INSERT INTO {0} ({1}) VALUES {2} ON CONFLICT ({3}) DO UPDATE SET {4}'.format(
            self.tables[0].get_identifier(),
            all_field_names_sql,
            row_values_sql,
            unique_field_names_sql,
            update_fields_sql
        )

        return self.sql, sql_args
Performs postgres upsert with multiple rows
dataset/ETHPy150Open ambitioninc/django-query-builder/querybuilder/query.py/Query.get_upsert_sql