Consider the case when the primary_key CHAR field is required to determine the ForeignKey relationship.
After some initial research, I identified the following possibilities, each with its own flaws:
1) Using 'primary_key = True'.
Example 1:
class Collection(models.Model): code = models.CharField(primary_key=True, max_length=3) class Item(models.Model): code = models.CharField(primary_key=True, max_length=255, unique=True) collection = models.ForeignKey('Collection', related_name='items')
Potential downside: a problem may arise when enabling third-party applications, as certain third-party django applications depend on the default integer PK id field.
2) Use the 'to_field' / 'through' option instead.
Example 2:
class Collection(models.Model): code = models.CharField(Max_length=3, unique=True) class Item(models.Model): collection = models.ForeignKey('Collection', to_field='code', related_name='items')
This will allow 'Collection' to have its own id primary_key, so it solves the problem of playing well with third-party django applications.
Potential disadvantages: after further study, I found the following open Django ORM tickets and errors regarding interaction with CHAR / INT primary_keys in FK and many-to-many relationships.
http://code.djangoproject.com/ticket/11319 and 13343
Conclusion:
Option 1 is better than Option 2.
But:
Are there many third-party applications that depend on the integer primary_key?
Is there an easy way around this limitation?
Are there any other disadvantages with CHAR primary_key?