Working with SObjects
SObject is the base class for Salesforce object models. It provides a Pythonic interface for working with Salesforce records.
Defining SObjects
Create a class that inherits from SObject
and define fields:
from sf_toolkit import SObject
from sf_toolkit.data.fields import IdField, TextField, NumberField, DateField, FieldFlag
class Account(SObject, api_name="Account"):
Id = IdField()
Name = TextField()
AnnualRevenue = NumberField()
Industry = TextField()
Rating = TextField()
Field Types
Salesforce Toolkit provides various field types that map to Salesforce field types:
TextField
- For string, text, picklist fieldsIdField
- For Salesforce ID fieldsNumberField
- For numeric fieldsIntField
- For integer fieldsCheckboxField
- For boolean fieldsDateField
- For date fieldsDateTimeField
- For datetime fieldsTimeField
- For time fieldsPicklistField
- For picklist fields with validationMultiPicklistField
- For multi-select picklist fieldsReferenceField
- For lookup/master-detail relationship fields
Field Flags
Field flags can be used to set properties on fields:
FieldFlag.nillable
- Field can be nullFieldFlag.unique
- Field must be uniqueFieldFlag.readonly
- Field cannot be modifiedFieldFlag.createable
- Field can be set on creationFieldFlag.updateable
- Field can be updated
CRUD Operations
Creating Records
# Create new record
account = Account(
Name="Test Account",
Industry="Technology",
Rating="Hot"
)
# Insert into Salesforce
account.save_insert()
Reading Records
# Retrieve by ID
account = Account.read("001xxxxxxxxxxxxxxx")
# Fetch multiple records
accounts = Account.list("001xxxxxxxxxxxxxxx", "001yyyyyyyyyyyyyyy")
Updating Records
account = Account.read("001xxxxxxxxxxxxxxx")
account.Name = "Updated Name"
account.Rating = "Warm"
# Update in Salesforce
account.save_update()
# Only send modified fields
account.save_update(only_changes=True)
Deleting Records
account = Account.read("001xxxxxxxxxxxxxxx")
account.delete()
Upsert with External ID
account = Account(
ExternalId__c="EXT123",
Name="New Account"
)
# Upsert based on external ID
account.save_upsert(external_id_field="ExternalId__c")
Dynamic SObject Creation
You can also create SObject classes dynamically from Salesforce metadata:
# Generate SObject class from describe metadata
Contact = SObject.from_description("Contact")
# Use the dynamically created class
contact = Contact(FirstName="John", LastName="Doe")
contact.save()