Issue
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
?
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.