I had a custom primary key that need to be set up on a particular data in a model.
This was not enough, as an attempt to insert a duplicate number succeeded. So now when i replace primary_key=True to unique=True it works properly and rejects duplicate numbers!!. But according this document (which uses fields).
primary_key=True implies null=False
and unique=True.
Which makes me confused as in why does
it accept the value in the first place
with having an inbuiltunique=True?
Thank you.
Updated statement:
personName = models.CharField(primary_key=True,max_length=20)
Use an
AutoFieldwithprimary_keyinstead.Edit:
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 needReportNumberto 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. anINSERT INTO(create a new DB record). Check out this line fromdjango.db.models.base.Model.save_base():Particularly, this snippet of code:
This says: “If a record with the same primary key as this
Modelexists 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 (
CharFieldor whatever) that has theuniqueconstraint.