Reputation: 73
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?
Upvotes: 0
Views: 2103
Reputation: 903
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)
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)
Upvotes: 1