Skip to content

Instantly share code, notes, and snippets.

@DmytroLitvinov
Last active February 10, 2017 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmytroLitvinov/b763f9ab7bd98a7fd7f8295c4390562a to your computer and use it in GitHub Desktop.
Save DmytroLitvinov/b763f9ab7bd98a7fd7f8295c4390562a to your computer and use it in GitHub Desktop.
Create unique slug field in Django models.
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