Skip to content

Instantly share code, notes, and snippets.

@ghickman
Created July 15, 2012 13:25
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 ghickman/3116929 to your computer and use it in GitHub Desktop.
Save ghickman/3116929 to your computer and use it in GitHub Desktop.
Generate unique slugs for Django models
from django.template.defaultfilters import slugify
def generate_slug(cls, value):
count = 1
slug = slugify(value)
if not isinstance(cls, type):
cls = cls.__class__
def _get_query(cls, **kwargs):
if cls.objects.filter(**kwargs).count():
return True
while _get_query(cls, slug=slug):
slug = slugify(u'{0}-{1}'.format(value, count))
# make sure the slug is not too long
while len(slug) > cls._meta.get_field('slug').max_length:
value = value[:-1]
slug = slugify(u'{0}-{1}'.format(value, count))
count = count + 1
return slug
from django.template.defaultfilters import slugify
@classmethod
def generate_slug(self, name):
count = 1
slug = slugify(name)
def _get_query(slug):
if MyModel.objects.filter(slug=slug).count():
return True
while _get_query(slug):
slug = slugify(u'{0}-{1}'.format(name, count))
# make sure the slug is not too long
while len(slug) > MyModel._meta.get_field('slug').max_length:
name = name[:-1]
slug = slugify(u'{0}-{1}'.format(name, count))
count = count + 1
return slug
@mjtamlyn
Copy link

Line 9 should be using exists() in both cases. There's not much difference in performance actually, but I think there would still be a small gain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment