Python Simple Salesforce:在联系人中为导入的联系人自动填充 AccountID

问题描述

我正在使用简单的 Salesforce Python 库将 10 个联系人从外部数据源导入 Salesforce。

背景一个帐户可以有多个联系人记录。我在帐户和联系人中都创建了一个 ExternalAccountID 字段。与要导入的 10 个联系人相关的帐户已加载到帐户对象中。帐户对象中的“ExternalAccountID”包含“旧帐户 ID”(例如 1234_LegacyAccountId)。

帐户中的“ExternalAccountID”字段是“外部”且唯一。 Contact 中的“ExternalAccountID”不是唯一的,因为每个帐户可以有多个联系人。

Contact 中的“ExternalAccountContactID”是“External”和“Unique”。此字段由旧帐户 ID + 旧联系人 ID 的串联组成。此字段用于更新联系人数据。

问题: Account 对象的“Id”未自动填充到“Contact”对象的 AccountId 字段中,10 个联系人的帐户已在 Account 对象中可用。

当前的解决方案使用 Pandas Dataframe 来更新 10 个联系人。这是查询源数据并在 Salesforce 目标服务器中更新数据的代码片段。

    information = sf.query_all(query= sql_code)
    table = pandas.DataFrame(information['records']).drop(columns='attributes')
    table['ExternalAccountID'] = table.Id 
    table['ExternalAccountContactID']=(table['AccountId'].astype(str)) +"_"+ 
    (table['Id'].astype(str))
    new_df = table[['Name','Email','ExternalAccountID','Department']]
    new_df = new_df.rename(columns= 
    {"ExternalAccountID":"ExternalAccountID__c","Name":"Name","Email":"Email","Department":"Department"})  
    results_json = new_df.to_json(orient='records')
    records_upsert = json.loads(results_json)
    print ("Records to be upserted")
    sft.bulk.Contact.upsert(records_upsert,'ExternalAccountContactID__c',batch_size=10000,use_serial=True)

我应该在脚本中的何处指定需要引用相关 Account 对象以便可以检索 Account 中的“Id”?在 Data Loader 中,我能够更新数据,并且 Contact 中的“AccountId”正在自动填充,如何使用 Python 实现相同的结果?任何提示

解决方法

假设 Account 上的 ext id 是 1234_LegacyAccountId,Contact 上的 ext id 是 1234_LegacyAccountId_1_Contact。

您需要的原始 REST API 请求类似于

https://yourInstance.salesforce.com/services/data/v52.0/sobjects/Contact/ExternalAccountContactID__c/1234_LegacyAccountId_1_Contact

{
   "FirstName" : "Joe","LastName" : "Bloggs","Email" : "example@example.com","Account" :
   {
       "ExternalAccountID__c" : "1234_LegacyAccountId" 
   }
}

这里写了一点:https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm

现在你需要弄清楚如何用 simple/pandas 来表示它。也许首先命名列 Account:ExternalAccountID__c (或带点)。也许熊猫允许对象作为列有效负载?

最坏的情况是您可以自己调用 REST,只需从 simple 的登录方法中窃取获取服务器和会话 ID 并手动制作 REST 调用。见https://github.com/simple-salesforce/simple-salesforce#additional-features

这种形式的 upsert 一次只能处理 1 条记录(因为您在 url 中传递了联系人的 ext id,您不能将多个联系人作为有效负载发送)。一旦掌握了单个调用,您就可以在单个请求中将它们批量处理多达 25 个(根据我的记忆,可能已经增加了),有点像我的回答 https://salesforce.stackexchange.com/a/274696/799

还有 https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_graph_introduction.htm 但我认为 simple 不支持,看起来有点黑魔法。