In part 3 of the simple-salesforce tutorial series, we are going to learn how to create, delete, update, and upsert records.


Buy Me a Coffee? Your support is much appreciated!
PayPal Me: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn





Source Code:

import json
import datetime
import pandas as pd
from simple_salesforce import Salesforce, SalesforceLogin, SFType

loginInfo = json.load(open('login.json'))
username = loginInfo['username']
password = loginInfo['password']
security_token = loginInfo['security_token']
domain = 'login'

session_id, instance = SalesforceLogin(username=username, password=password, security_token=security_token, domain=domain)
sf = Salesforce(instance=instance, session_id=session_id)

project__c = SFType('Project__c', session_id, instance)

today = datetime.datetime.now()

data = {
   'Name': 'Project Yellowstone' ,
   'Priority__c': 'High',
   'Start_Date__c': today.isoformat() + 'Z',
   'End_Date__c': (today + datetime.timedelta(days=45)).isoformat() + 'Z'
}

response = project__c.create(data)
print(response)


"""
Parent-Child Relationship Record creation
"""
project__c = SFType('Project__c', session_id, instance)
account = SFType('Account', session_id, instance)

for i in range(1, 6):
    data_account = {'Name': 'Retail Account ' + str(i), 'Type': 'Prospect'}
    response_account = account.create(data_account)
    accountId = response_account.get('id')

    data_project = {'Name': 'Project Yosemite ' + str(i), 'Customer_Account__c': accountId}
    response_project = project__c.create(data_project)
    projectId = response_project.get('id')

    print('Record Created')
    print('-'.center(50, '-'))
    print('Account Id: {0}'.format(accountId))
    print('Project Id: {0}'.format(projectId))


"""
Update Record
"""
def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0):
    dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'
    return dt

year = 2020
month = 5
day = 15

update_data = {}
update_data['Budget__c'] = 300_000
update_date['Start_Date__c'] = convert_to_RFC_datetime(year, month, day)
update_data['End_Date__c'] = convert_to_RFC_datetime(year, month + 5, 1)
update_data['Priority__c'] = 'Medium'

response_project.get('id')

project__c.update(response_project.get('id'), update_data)