Skip to content

Instantly share code, notes, and snippets.

@ghickman
Created Jul 15, 2012
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@mjtamlyn mjtamlyn commented Apr 13, 2015

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