简体   繁体   中英

django.db.utils.IntegrityError: UNIQUE constraint failed:

I am making review api with django, but I have a problem.

models.py

from django.db import models
import uuid

# Create your models here.
from django.utils.text import slugify

class buildingData(models.Model):
    building_name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(unique=True, default=uuid.uuid1)
    building_loc = models.CharField(max_length=50)
    building_call = models.CharField(max_length=20)
    building_time = models.CharField(max_length=50)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.building_name)
        return super().save(*args, **kwargs)
        

class reviewData(models.Model):
    building = models.ForeignKey(buildingData, related_name='reviews', on_delete=models.CASCADE, null=False, blank=False)
    review_content = models.TextField()
    star_num = models.FloatField()

urls.py

from django.contrib import admin
from django.urls import path
from crawling_data.views import ReviewListAPI
from crawling_data.views import BuildingInfoAPI

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/buildingdata/', BuildingInfoAPI.as_view()),
    path('api/buildingdata/<slug:slug>/', ReviewListAPI.as_view())
]

I am collecting data with crawling, but...

django.db.utils.IntegrityError: UNIQUE constraint failed: crawling_data_buildingdata.slug

This error occurs.

I've tried deleting migrate file and migration again, but still doesn't work.

Is there any problem on my code or is there other way to solve this?

That is because the uuid1 is generated from your machine ID and time stamp and the machine ID in your case remains constant, that's why they look pretty similar at the end. You may use uuid4() to get a random unique UUID.

Answer from @ZdaR in this answer

You should change the first model to this:

class buildingData(models.Model):
    building_name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(unique=True, default=uuid.uuid4)
    building_loc = models.CharField(max_length=50)
    building_call = models.CharField(max_length=20)
    building_time = models.CharField(max_length=50)

Also you can use your slug as primary key with this:

slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

Edited:

I see your save function. in your save function you should remove the slug assignment. Or change it to self.slug = None . If you want to have a slug from the building name you must use TextField or CharField in the model:

slug = models.TextField(unique=True, default=uuid.uuid4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM