Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django abstract parent model save overriding

I'm trying to write an abstract parent model in Django which will help me making some slug field from name field for many other child models. It uses trans encoding which works perfect for translitterating form cyrillic to latin letters. Then it uses slugify function from django to remove garbage.

class SlugModel(models.Model):
    class Meta:
        abstract = True

    name = models.CharField(max_length=128, default=u'')
    slug = models.CharField(max_length=128,blank=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(unicode(self.name).encode('trans'))
        else:
            slug = self.slug
        count = self.__class__.objects.filter(slug = slug).count()
        if count > 1:
            if slug[-2]=='_':
                count = int(slug[-1])
                slug = slug[:-2]
            self.slug = '{0}_{1}'.format(slug,count+1)
        else:
            self.slug = slug
        super(self.__class__, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name



class Foo(SlugModel):
    pass

The problem occurs when I'm trying to save some Foo object: it causes RuntimeError (maximum recursion depth exceeded). What am I doing wrong? How do I write super(self.__class__, self).save(*args, **kwargs) correctly?

like image 713
Павел Тявин Avatar asked Nov 18 '12 14:11

Павел Тявин


People also ask

When to override save method Django?

Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField.

How to save model in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What is abstract inheritance in Django?

What is Django Abstract Base Class Model Inheritance ? According to Django Documentation Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class.


2 Answers

Just use super().save(*args, **kwargs).

like image 85
gornvix Avatar answered Oct 19 '22 19:10

gornvix


Ok, I got it. Instead of using super(self.__class__, self).save(*args, **kwargs).

I needed super(SlugModel, self).save(*args, **kwargs).

Thanks to peppergrower.

like image 40
Павел Тявин Avatar answered Oct 19 '22 18:10

Павел Тявин