這是Django的文檔:Django的獨特=真不工作
Field.unique
If True, this field must be unique throughout the table.
This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django .db.IntegrityError will be raised by the model’s save() method.
這裏是我的models.py
class MyModel(models.Model):
# my pk is an auto-incrementing field
url = models.URLField("URL", unique=True)
text = models.TextField(max_length=1000)
# my model is just two fields, one pk (unique), and another unique field,
#, the url
這裏我是manage.py sqlall(我跑了執行syncdb)
CREATE TABLE `MyModel_mymodel` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`url` varchar(200) NOT NULL UNIQUE,
`text` varchar(1000) NOT NULL,
但是,在manage.py shell中,我可以自由地做到這一點:
>>> from MyModel.models import MyModel
>>> MyModel().save() # it works fine!? Not even the text was checked for!
>>> MyModel(url="blah").save()
>>> MyModel(url="blah").save() # it still works!
# I checked the mysql database afterwards, the models were saved just fine, they
# however did have different PK's (auto incrementing fields).
我使用的是mysql,django 1.5。有沒有人有一個想法有可能造成這種情況?
我正在使用自定義管理器,但我懷疑這是問題所在。
謝謝。
我'IntegrityError:列網址是不是第二個'爲MyModel(URL = 「嗒嗒」)unique'例外保存()'。你是否按原樣粘貼了你的代碼? – falsetru
'text'字段定義有錯字..'模式'。我懷疑你沒有複製和粘貼你的代碼。 – falsetru
不,我不認爲代碼需要張貼,只有兩個領域值得注意 –