[Django]-Primary key and unique key in django


Use an AutoField with primary_key instead.


If you don’t use an AutoField, you’ll have to manually calculate/set the value for the primary key field. This is rather cumbersome. Is there a reason you need ReportNumber to the primary key? You could still have a unique report number on which you can query for reports, as well as an auto-incrementing integer primary key.

Edit 2:

When you say duplicate primary key values are allowed, you indicate that what’s happening is that an existing record with the same primary key is updated — there aren’t actually two objects with the same primary key in the database (which can’t happen). The issue is in the way Django’s ORM layer chooses to do an UPDATE (modify an existing DB record) vs. an INSERT INTO (create a new DB record). Check out this line from django.db.models.base.Model.save_base():

if (force_update or (not force_insert and
    # It does already exist, so do an UPDATE.

Particularly, this snippet of code:


This says: “If a record with the same primary key as this Model exists in the database, then do an update.” So if you re-use a primary key, Django assumes you are doing an update, and thus doesn’t raise an exception or error.

I think the best idea is to let Django generate a primary key for you, and then have a separate field (CharField or whatever) that has the unique constraint.


Leave a comment