I'm querying Salesforce via the python package, Simple_Salesforce.
The results are returned as an OrderdDict.
I would like to convert the records to a simple list of lists (although in the sample there is only 1 record). This is very easy to do, except in this example, the field Approval_Date__c
comes from a related table via a SOQL join. This appears to get returned as a nested OrderedDict. I am unable to generate the list with this value included. I get KeyError: 'Opportunity__r'
My Code:
import collections
orderedDict = collections.OrderedDict()
from collections import OrderedDict
query_results = OrderedDict([(u'totalSize', 1), (u'done', True), (u'records', [OrderedDict([(u'attributes', OrderedDict([(u'type', Orders__c'), (u'url', u'someurl')])), (u'Id', u'a4T13000000sdfd'), (u'Order_Type__c', u'Standard'), (u'Opportunity__c', u'006130000145451245'), (u'Opportunity__r', OrderedDict([(u'attributes', OrderedDict([(u'type', u'Opportunity'), (u'url', u'someurl1')])), (u'Approval_Date__c', u'2014-12-31')]))])])])
List_Results = [[record['Id'], record['Order_Type__c'], [[record['Approval_Date__c']] for record in query_results['Opportunity__r']]] for record in query_results['records']]
print List_Results
Desired Result:
[[u'a4T13000000sdfd', u'Standard', u'2014-12-31']]
Simple conversation excluding the field from the nested OrderedDict to prove it works:
List_Results = [[record['Id'], record['Order_Type__c']] for record in query_results['records']]
You're getting the key error because you're trying to look up Opportunity__r
in query_results, which doesn't have an Opportunity__r
key. Instead, Opportunity__r
is a key in the record
.
I think what you want is:
List_Results = [[record['Id'], record['Order_Type__c'], record['Opportunity__r']['Approval_Date__c']] for record in query_results['records']]