2

I am trying to create unique slugs from persons names, which will have obvious duplicates. My idea is to add the id to the slug as a unique identifier. The problem is that the unique id is not generated until the save completes.

This is what I tried:

def save(self, *args, **kwargs):

        if getattr(self, 'name', True):

            if not self.pk:
                matching_slugs = Entity.objects.filter(slug=slugify(self.name))
                print matching_slugs
                if len(matching_slugs) > 0:
                    self.slug=slugify(self.name+' temp')
                elif len(matching_slugs) == 0:
                    self.slug=slugify(self.name)
        super(Entity, self).save(*args, **kwargs)
        self.slug=slugify(self.name+' '+str(self.id))
        self.save()

I get the error:

maximum recursion depth exceeded in cmp

I'm thinking this is not the best way to do this.

How can I make names unique on save?

Atma
  • 29,141
  • 56
  • 198
  • 299
  • Just delete `self.save()` – amarynets Sep 27 '17 at 20:43
  • But why you do not use https://docs.djangoproject.com/en/1.11/ref/models/fields/#slugfield with `unique=True` – amarynets Sep 27 '17 at 20:47
  • Do you specifically need the slug to be `name` + `pk` or do you just need a unique slug? It may help if you tell us how you want to use this slug. – petroleyum Sep 27 '17 at 20:53
  • @AndMar is right that the `self.save()` is the cause of the recursion error, but it looks like you want to use `self.id` which isn't set until the object is first saved so I can see why you are trying to save it twice. This post may help with saving an object twice: https://stackoverflow.com/a/14236946/1051031 – petroleyum Sep 27 '17 at 20:57

2 Answers2

3

May be you can use simple construction?:

import uuid


def save(self, *args, **kwargs):
    if not self.slug:
          self.slug = "%s.%s" % (self.name , uuid.uuid4())
    super(Entity, self).save(*args, **kwargs)
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
0

I changed the save() to be:

    super(Entity, self).save(*args, **kwargs)
    self.slug=slugify(self.name+' '+str(self.id))
    super(Entity, self).save(*args, **kwargs)
Atma
  • 29,141
  • 56
  • 198
  • 299