简体   繁体   中英

how to call a method that is out of the class and pass the class instance to it in python django

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM