Created
July 15, 2012 13:25
-
-
Save ghickman/3116929 to your computer and use it in GitHub Desktop.
Generate unique slugs for Django models
This file contains hidden or 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.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 |
This file contains hidden or 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.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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.