Skip to content

Instantly share code, notes, and snippets.

@maxpoletaev
Created February 7, 2019 20:31
Show Gist options
  • Save maxpoletaev/b1c83611090bb446e44b7a2d0bcd5729 to your computer and use it in GitHub Desktop.
Save maxpoletaev/b1c83611090bb446e44b7a2d0bcd5729 to your computer and use it in GitHub Desktop.
def unique_slug(queryset, source, pk, slug_field='slug'):
slug_base = slugify(source)
slug = slug_base
index = 1
if isinstance(queryset, ModelBase):
queryset = queryset.objects.all()
while True:
if not queryset.filter(**{slug_field: slug}).exclude(pk=pk).exists():
return slug
slug = f'{slug_base}-{index}'
index += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment