49
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
.)
1
Running sql scripts directly on the db can be avoided. Rather add the sql execution in your migration:
from __future__ import unicode_literals
from django.db import migrations, connection
def alter_table(apps, schema_editor):
query ="ALTER TABLE <your table> ADD UNIQUE (unique_col);"
cursor = connection.cursor()
cursor.execute(query)
cursor.close()
class Migration(migrations.Migration):
dependencies = [
('app', 'yourlastmigration'),
]
operations = [
migrations.RunPython(alter_table),
]
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
- [Django]-Iterate over model instance field names and values in template
- [Django]-How can I iterate over ManyToManyField?
0
The solution is pretty simple, Just follow their steps.
1 - Dell all the files in the migration folder
2 - Then run the command "python manage.py makemigrations"
3 - Then run the command "python manage.py migrate"
OR
Do it by the help of a simple SQL-lite Query Adding index Example
alter table test add index index_name(col1(255),col2(255));
Adding unique index Example
alter table test add unique index_name(col1(255),col2(255));
- [Django]-Django β [Errno 111] Connection refused
- [Django]-Are sessions needed for python-social-auth
- [Django]-Django change default runserver port