What are the full consequences of not using the default "id" primary_key in your Django model?

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?

+4
source share
3 answers

GenericForeignKey suffer as they all must use the same type for foreign PK. As long as you stay away from them, you should be fine.

+1
source

I am having problems in admin django application when using char field as primary key. See unicode error when saving an object in django admin for more details.

Recovering id as a primary key was difficult; see What is the best approach for changing primary keys in an existing Django application? .

From this experience, I think using something other than id as the primary key is a bad idea.

+1
source

I personally go to option 2 in my applications, since I saw how most third-party applications do it, and this avoids a lot of problems that you already raised in your message regarding mixing CHAR and INT primary keys in ORM Django.

I did not encounter one problem, but just used unique=True , so I really don't see any flaws in that.

0
source

All Articles