1

I have a model named Klass with below code:

class Klass(models.Model):
title = models.CharField(max_length=50, verbose_name='class name')
slug = models.SlugField(default=slug_generator, allow_unicode=True, unique=True)

and it's the slug_generator function that is out of the class.

def slug_generator(instance, new_slug):
    if new_slug is not None:
        slug = new_slug
    else:
        slug = slugify(instance.title)

    Klass = instance.__class__
    qs_exists = Klass.objects.filter(slug=slug).exists()
    if qs_exists:
        new_slug = "{slug}-{randstr}".format(
            slug=slug,
            randstr=random.randint(100000,999999)
        )
        return unique_slug_generator(instance, new_slug=new_slug)
    return slug

in order to creating unique slugs, I want to use this function. i want to use this function for some other models. how can i pass the class to it?

msln
  • 1,318
  • 2
  • 19
  • 38
  • Why not define the `__init__` constructor and apply a unique ID generator in there along with any other instance properties you want? – marchWest Aug 18 '17 at 17:43
  • @marchWest as i said, i want to use a function for some models, because i have 6 models that need unique slug according to their title properties. i don't want to write a code 6 times! – msln Aug 18 '17 at 17:46
  • 2
    @MojtabaSalehiyan You can create an [abstract base class](https://docs.djangoproject.com/en/1.11/topics/db/models/#abstract-base-classes) with common methods and inherit your models from this base class. You won't have to write the code 6 times. – xyres Aug 18 '17 at 17:54
  • In any case, a default value cannot depend on other data in the instance; apart from anything else, there *isn't* any other instance data at the point that the default is applied. Do this in the `save` method. – Daniel Roseman Aug 18 '17 at 18:35

1 Answers1

1

You can create a abstract class that the other class hierachy from it, I don't check the code, but it is something like that

class Slug(models.Model):

    class Meta:
        abstract = True

    def slug_generator(instance, new_slug):
       if new_slug is not None:
       ....

and then:

class Klass(Slug):
.....
Roberto
  • 532
  • 7
  • 20