Last active
February 10, 2017 10:05
-
-
Save DmytroLitvinov/b763f9ab7bd98a7fd7f8295c4390562a to your computer and use it in GitHub Desktop.
Create unique slug field in Django models.
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
def save(self, *args, **kwargs): | |
self.do_unique_slug() | |
super(Klass, self).save(*args, **kwargs) | |
def do_unique_slug(self): | |
""" | |
Ensures that the slug is always unique for this post | |
""" | |
if not self.id: | |
# make sure we have a slug first | |
if not len(self.slug.strip()): | |
self.slug = slugify(self.title) | |
self.slug = self.get_unique_slug(self.slug) | |
return True | |
return False | |
def get_unique_slug(self, slug): | |
""" | |
Iterates until a unique slug is found | |
""" | |
orig_slug = slug | |
counter = 1 | |
while True: | |
objects = Klass.objects.filter(slug=slug) | |
if not objects.exists(): | |
return slug | |
slug = "{}{}".format(orig_slug, counter) | |
counter += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment