Search code examples
djangoclassmodels

Django Models Option Save


i just want to ask how it works that method "save", in this model? I just trying to add this to my code, but i really dont know how it works.. Those lines help me to save the slugify if theres is not an id in the model? Thank you so much.

class Category(models.Model):

    name = models.CharField(max_length=50)
    slug = models.SlugField(editable=False)

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

Solution

  • Short answer: this helps you to add slug into new object.

    To check if object is new you perform this validation:

    if not self.id:
    

    this return True only if self.id is empty. Considering id is primary key it is only possible for new object.

    self.slug = slugify(self.name)
    

    Now you convert name field into slug using slugify util:

    Converts to ASCII if allow_unicode is False (default). Converts spaces to hyphens. Removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

    For example:

    slugify(value)

    If value is "Joel is a slug", the output will be "joel-is-a-slug".

    And finally you call

    super(Category, self).save(*args, **kwargs)
    

    to save object.