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?
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.
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 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.
Just use super().save(*args, **kwargs)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With