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?
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):
.....