I am curious about Django database model pk.
Is there any difference this
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=50)
between this?
class Category(models.Model):
category_name = models.CharField(max_length=50)
Are the same things AutoField with primary_key
and default pk
?
pk is the attribute that contains the value of the primary key for the model. id is the name of the field created as a primary key by default if none is explicitly specified.
According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.
Every table should have a primary key, so every model should have a primary key field. However, you do not have to do this manually if you do not want. By default, Django adds an id field to each model, which is used as the primary key for that model.
Starting new projects in Django 3.2, the default type for primary keys is set to a BigAutoField which is a 64 bit integer.
Yes, the difference is, the column name in the database for the primary key is category_id
and in the second case is id
.
One way you can make the second example emulate the first one is:
class Category(models.Model):
category_name = models.CharField(max_length=50)
@property
def category_id(self):
return self.id
From the documentation,
AutoField
An IntegerField that automatically increments according to available IDs. You usually won’t need to use this directly; a primary key field will automatically be added to your model if you don’t specify otherwise
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With