首页 > 解决方案 > Python Simple Salesforce:为导入的联系人自动填充联系人中的 AccountID

问题描述

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

背景:一个帐户可以在联系人中有多个记录。我在 Account 和 Contact 中都创建了 ExternalAccountID 字段。与正在导入的 10 个联系人相关的帐户已加载到 Account 对象中。Account 对象中的'ExternalAccountID' 包含'legacy account id'(例如1234_LegacyAccountId)。

Account 中的“ExternalAccountID”字段为“External”且唯一。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 实现相同的结果?任何提示

标签: pythondataframesalesforcesimple-salesforce

解决方案


假设 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 调用,只需从简单的登录方法中窃取服务器和会话 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但我不认为简单的支持,看起来有点黑魔法。


推荐阅读