from django.db import IntegrityError
from django.template.defaultfilters import slugify


def save_obj_with_slug(obj, attribute='title', **kwargs):
    obj.slug = slugify(getattr(obj, attribute))
    return save_obj_unique(obj, 'slug', **kwargs)


def save_obj_unique(obj, attr, count=0, postfix_format='-{count}'):
    klass = obj.__class__
    MAX_COUNT = 10000  # max 10 thousand loops
    base_attr = getattr(obj, attr)
    initial_count = count
    first_round = count == 0
    postfix = ''
    while True:
        try:
            while initial_count - count < MAX_COUNT:
                if not first_round:
                    postfix = postfix_format.format(count=count)
                if not klass.objects.filter(**{
                            attr: getattr(obj, attr) + postfix
                        }).exists():
                    break
                if first_round:
                    first_round = False
                    count = klass.objects.filter(**{
                        '%s__startswith' % attr: base_attr
                    }).count()
                else:
                    count += 1
            setattr(obj, attr, base_attr + postfix)
            obj.save()
        except IntegrityError:
            if count - initial_count < MAX_COUNT:
                first_round = False
                count = klass.objects.filter(**{
                    '%s__startswith' % attr: base_attr
                }).count()
            else:
                raise
        else:
            break

@@ -937,32 +937,61 @@
          count =
+ max(%0A                       
  klass.objects.f
@@ -992,32 +992,36 @@
 ects.filter(**%7B%0A
+    
                 
@@ -1075,32 +1075,36 @@
                 
+ 
+   
 %7D).count()%0A     
@@ -1089,32 +1089,93 @@
       %7D).count()
+,%0A                        initial_count%0A                    )
 %0A               
@@ -1360,32 +1360,68 @@
 nt %3C MAX_COUNT:%0A
+                if first_round:%0A    
                 
@@ -1456,23 +1456,56 @@
         
+  
+  
 count =
+ max(%0A                       
  klass.o
@@ -1534,32 +1534,40 @@
                 
+   
+     
 '%25s__startswith'
@@ -1593,32 +1593,40 @@
                 
+        
 %7D).count()%0A     
@@ -1619,16 +1619,104 @@
 .count()
+,%0A                        initial_count%0A                    )%0A                count += 1
 %0A       

Fix bad initial count in slug creation helper