问题
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 inbuilt
unique=True
?
Thank you.
Updated statement:
personName = models.CharField(primary_key=True,max_length=20)
回答1:
Use an AutoField with primary_key
instead.
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 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
manager.using(using).filter(pk=pk_val).exists())):
# It does already exist, so do an UPDATE.
Particularly, this snippet of code:
manager.using(using).filter(pk=pk_val).exists()
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.
来源:https://stackoverflow.com/questions/6039443/primary-key-and-unique-key-in-django