Django pk VS id
If you don’t specify primary_key=True for any fields in your model, Django will automatically add an IntegerField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior.
The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one
Example:
suppose we have this model. In this model we have make email field as primary key. now django default primary key id field will be gone. It'll remove from database. we can not query as
UserProfile.objects.get(id=1)
after make email as primary key this query will throw an error.
Now we have to use pk
UserProfile.objects.get(pk="admin@admin.com")
In Conclusion
In Django, the choice between “id”and “pk” primarily comes down to the specific requirements of your project. “id” is a great choice for most scenarios due to its efficiency and simplicity. However, if you have specific needs for a custom primary key, then “pk” is the way to go.
Comments
Post a Comment