To create a Django model with a SlugField
that must be unique, you simply need to set the unique
parameter to True
when defining the field. Here's how you can do it:
pythonfrom django.db import models
class YourModel(models.Model):
# Define other fields of your model here
# Define SlugField with unique option
slug = models.SlugField(unique=True, max_length=255)
def __str__(self):
return self.slug
In this example:
models
module from django.db
.YourModel
, inheriting from models.Model
.slug
field using models.SlugField
.unique=True
to ensure that each slug is unique within the database.max_length
to limit the length of the slug.__str__
method to return a string representation of the model instance, which in this case is the slug.With this setup, Django will enforce uniqueness for the slug
field in the database, ensuring that each instance of YourModel
has a unique slug value. If you attempt to create or update a model instance with a non-unique slug value, Django will raise a django.db.utils.IntegrityError
.