How to create a Django model with a SlugField and unique option



Image not found!!

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:

python
from 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:

  • We import the models module from django.db.
  • We define a model class named YourModel, inheriting from models.Model.
  • We define other fields of the model according to your requirements.
  • We define a slug field using models.SlugField.
    • We set unique=True to ensure that each slug is unique within the database.
    • We can also set max_length to limit the length of the slug.
  • We define a __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.