Salesforce foreign key field name

146 views Asked by At

In our project we use Salesforce library in Django. We have class which include the raw:

class SalesforceContact(models.Model):
    account = models.ForeignKey(SalesforceAccount, models.DO_NOTHING,
            db_column='AccountId', blank=True, null=True, related_name='contacts')

When we get the result all_contacts = SalesforceContact.objects.filter(xxxxxxx).all() the attributes of all_contacts doesn't contain 'account' but 'account_id' field.

It's not API so I'm not using serializers.

Am I wrong and there is a bug? How can I change the name of attribute?

1

There are 1 answers

0
hynekcer On

It is normal in Django that you see only the foreign key in an attribute "..._id". If you look at it by all_contacts[0].__dict__ then you don't see any "account". You can access it as a whole foreign object by all_contacts[0].account or getattr(all_contacts[0], "account"). It is implemented in Django by a special magic method __getattr__ that is used if a normal attribute is not found. This is because foreign objects in Django are usually "lazy evaluated" when they are really needed, not initially when the main object is loaded and maybe the foreign object will be not used.

This is not anything special in django-salesforce or Salesforce. You can read about it in Django documentation. Even if you load both the main and the related data together by a select_related() method then you can access the "account" fast, but it is also similarly accessed under the hood by the magic __getattr__ method.