Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django AutoField with primary_key vs default pk

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?

like image 988
fatiherdem Avatar asked Aug 08 '14 13:08

fatiherdem


People also ask

What is the difference between ID and PK in Django?

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.

How does Django AutoField work?

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.

Does every Django model have a primary key?

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.

What is default auto field in Django?

Starting new projects in Django 3.2, the default type for primary keys is set to a BigAutoField which is a 64 bit integer.


1 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

like image 137
karthikr Avatar answered Oct 19 '22 03:10

karthikr