Consider the case where a CHAR field primary_key is required in order to define a ForeignKey relationship.
After some initial investigation I have identified the following possibilities, each with their own drawbacks:
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 Drawback: Might result in issues when incorporating 3rd party apps as certain 3rd party django apps depend on the default 'id' PK integer 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 nicely with 3rd party django apps.
Potential drawbacks: After further investigation I discovered the following open Django ORM tickets and bugs with regards to dealing with mix of 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.
However:
Are there many 3rd party apps that depend on the integer primary_key?
Is there an easy workaround for this limitation?
Are there any other drawbacks using a CHAR primary_key?