django-salesforce foreign key syntax

627 views Asked by At

I'm using django-salesforce to get a list of Contacts (child) and the Accounts (parent) associated with them.

In my models.py, what is the syntax for defining a field in the Contact class to hold the Account name?

Here's my models.py:

from django.db import models
from salesforce.models import SalesforceModel

class Account(SalesforceModel):
    Name = models.CharField(max_length=255)

    def __unicode__(self):
        return u'%s %s' % (self.Name, self.Id)

class Contact(SalesforceModel):
    FirstName = models.CharField(max_length=255)
    LastName = models.CharField(max_length=255)
    AccountId = models.CharField(max_length=255)

    def __unicode__(self):
        return u'%s %s %s' % (self.FirstName, self.LastName, self.AccountId)

I've not been able to find any examples, but I was thinking it would look something like this:

AccountName = models.ForeignKey(Account, db_column='Name')
2

There are 2 answers

6
David Robinson On

The account name shouldn't be held in a field in Contact, since it's already held in Account (this is the purpose of database normalization- to reduce redundancy).

Instead you would connect it using a single ForeignKey:

class Contact(SalesforceModel):
    FirstName = models.CharField(max_length=255)
    LastName = models.CharField(max_length=255)
    Account = models.ForeignKey(Account)

and get the account name from a Contact object c with:

c.Account.Name
2
Phil Christensen On

I'm the author of django-salesforce. You shouldn't have to do anything too special to make a Foreign Key relationship work, although you will likely need to be explicit about your key names. Here's a very trivial example, found in the example app contained in the source tarball:

class User(SalesforceModel):
    Email = models.CharField(max_length=100)
    LastName = models.CharField(max_length=80)
    FirstName = models.CharField(max_length=40)
    IsActive = models.BooleanField()

class Account(SalesforceModel):
    Owner = models.ForeignKey(User, db_column='OwnerId')

Because the default Salesforce naming conventions are different than Django's, you must explicitly tell it the name of your foreign key field. Otherwise it will use the Django convention of appending '_id' rather than the SF convention of appending 'Id'

Then, similar to that mentioned in David's response, you'd access the first name of an account owner with:

a = models.Account.objects.all()[0]
print a.Owner.FirstName