'django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug
I'm learning Django from Tango with Django but I keep getting this error when I type:
python manage.py makemigrations rango
python manage.py migrate
This is the output:
django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug
Models.py:
from django.db import models
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
Solution 1:[1]
The reason for this constrain could be that you didn't have any field called slug
in Category
class when you have initially migrated it (First Migration), and after adding this field in the model, when you ran makemigrations
, you have set default value to something static value(i.e None
or ''
etc), and which broke the unique constrain for the Category's table's slug column in which slug should be unique but it isn't because all the entry will get that default value.
To solve this, you can either drop the database and migration files and re-run makemigrations
and migrate
or set a unique default value like this:
slug = models.SlugField(unique=True, default=uuid.uuid1)
Edit:
According to Migrations that add unique fields, modify your migration file to overcome unique constrain. For example, modify your migration file (which added the slug field to the model) like this:
import uuid
from app.models import Category # where app == tango_app_name
class Migration(migrations.Migration):
dependencies = [
('yourproject', '0003_remove_category_slug'),
]
def gen_uuid(apps, schema_editor):
for row in Category.objects.all():
row.slug = uuid.uuid4()
row.save()
operations = [
migrations.AddField(
model_name='category',
name='slug',
field=models.SlugField(default=uuid.uuid4),
preserve_default=True,
),
migrations.RunPython(gen_uuid),
migrations.AlterField(
model_name='category',
name='slug',
field=models.SlugField(default=uuid.uuid4, unique=True),
),
]
Solution 2:[2]
I got a field with attribute unique, which was not unique [eg 2-time same value]
python3 manage.py migrate --fake
then
python3 manage.py makemigrations
python3 manage.py migrate
this did the trick
Solution 3:[3]
This means a slug should be unique. You may have some data in your model. You need to delete all the data in that model and you need to migrate again.
In this situation, you have two ways to fix the error;
You need to delete it from the
Django admin
site. More often than not, it may give an error when you are trying to open the model.Open command prompt
move to project -> py manage.py shell -> from yourappname.models import modelname -> modelname.objects.delete()
Here if you define a product manager for your model. Then you have to define a delete function. Later you should makemigrate
, migrate
and continue with the second way
Solution 4:[4]
I had the same problem and tried all the suggested answers. What finally worked for me was, after I defined the slug field as a URL in models, and ran the makemigrations. I edited the file in makemigrations adding a random number at the end of a basic URL, like this
Generated by Django 3.2.3 on 2022-02-02 20:58
from django.db import migrations, models from random import randint
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_remove_post_slug1'),
]
operations = [
migrations.AddField(
model_name='post',
name='slug',
field=models.URLField(blank=True, default='http:/salpimientapa.com/' + str(randint(100000,999999))),
),
]
After I ran python manage.py migrate
I edit the slug as a SlugModel and ran the makemigrations and migrate again
Solution 5:[5]
What worked for me was going to the admin and changing the value of duplicate slug, before running the migrations again.
Solution 6:[6]
I just met this simiilar error: Django UNIQUE constraint failed. I tried examine the code for very long time, but didn't solve it. I finally used SQLiteStudio to examine the data, and found the data is problematic: I unintentionally added two SAME instances which violates the UNIQUE constraint. To be frank I haven't thought the error could be this naive and simple, and because so it took me a lot of time to find out!
Solution 7:[7]
Just delete the last migration in the migration folder
Then run
python manage.py makemigrations
python manage.py migrate
Solution 8:[8]
I faced the same issue and solved by populating my slugfied thro' the admin with unique values and without leaving any of them blank.
Solution 9:[9]
Basically: You add the field without unique=true in one operation, make a data migration that generates the correct shortuuids for you, and then change the field too unique again.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow