Setting primary key to true in a model field

In what cases would you want to set primary key to true.

By default, Django will create a primary key field as an integer, named ‘id’. However, there may be times / situations where it is more suitable for your app to define your own primary key - either or both of a different type or name.

In that case, you would want to define your primary key as the desired field and indicate such with primary_key=True in the field definition.

We use it frequently in our applications for specifying choices for selections, to both ensure referential integrity and to allow choice selections to be managed outside of code. (To be clear - this is not the only reason why you might choose to do this - this is just one example.)

For example, we have a model whose complete definition is as follows:

class FirmType(models.Model):
    firm_type = models.CharField('Firm Type', max_length=20, primary_key=True)

    def __str__(self):
        return self.firm_type

that means that other models having a field named firm_type can be defined as a foreign key to FirmType. This ensures that only valid FirmTypes are selected by those other models, and we can add FirmTypes to a deployed instance without making a code change.
(We call these “code tables”, although a database purist would disagree with using that term here.) We have somewhere in the neighborhood of 10 - 15 such tables in one of our apps.

(Note, we only use this pattern for “internal” or “infrastructure” tables. This is never done for any table modifiable by an end user.)


1 Like

thanks for the explanation. I have a better understanding now.