Last active
April 20, 2022 22:26
-
-
Save jaradc/e81ba39a688297ead0bb8134a9fec358 to your computer and use it in GitHub Desktop.
Simple-stupid way to guarantee slug uniqueness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.utils.text import slugify | |
class Content(models.Model): | |
title = models.CharField(max_length=100) | |
slug = models.SlugField(max_length=100) | |
def save(self, *args, **kwargs): | |
# simple-stupid way to guarantee slug uniqueness | |
n = 1 | |
base_slug = slugify(self.title) | |
slug = base_slug | |
while self.__class__.objects.filter(slug=slug).exists(): | |
slug = f'{base_slug}-{n}' | |
n += 1 | |
self.slug = slug | |
super().save(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment