Django AutoField with primary_key vs default pk

Question:

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?

Asked By: fatiherdem

||

Answers:

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

Answered By: karthikr

The difference is field name.

For example, I definded the model "Category" with the field "category_id":

# "myapp/models.py"

from django.db import models

class Category(models.Model):
    category_id = models.AutoField(primary_key=True)
    category_name = models.CharField(max_length=50)

Then, run this command below:

python manage.py makemigrations && python manage.py migrate

Now, I opened "db.sqlite3" then the field name is "category_id":

enter image description here

Next, I definded the model "Category" without the field "category_id":

# "myapp/models.py"

from django.db import models

class Category(models.Model):
   category_name = models.CharField(max_length=50)

Then, run this command below:

python manage.py makemigrations && python manage.py migrate

Now, I opened "db.sqlite3" then the field name is "id":

enter image description here

Buy me a coffee!!

Answered By: Kai – Kazuya Ito