Django unique=True not working

后端 未结 3 1471
暗喜
暗喜 2020-12-23 18:03

This is from django\'s documentation:

Field.unique

If True, this field must be unique throughout the table.

This is enforced at the databas

3条回答
  •  臣服心动
    2020-12-23 18:23

    For django 1.9+
    Running makemigrations then migrate applies the unique constraint to sqlite3

    For django < 1.9
    Since you are using django 1.5, this solution will apply.

    If you added the unique=True after the table was already created, then even if you do syncdb later, the unique condition will not be added to your table.

    I can confirm with sqlite3 that Django 1.5 happily saves duplicate objects with MyModel(url="blah").save() if the unique constraint does not exist in the database, which seems to contradict with the docs.

    The best solution for you is to create the constraint manually in your database using this command.

    ALTER TABLE MyModel_mymodel ADD UNIQUE (url);
    

    Or if you don't mind, you can recreate your table. (Drop the table and then run syncdb.)

提交回复
热议问题