How to add calculated default value to Django model?

Viewed 30

I want to add slug field in existing model and the value should be calculated with Django's slugify function based on title field. How can this be done? I understand that I can override save method of the model class and do all stuff there, it will work for all future saved instances, but is there an elegant way to populate this field for existing rows also?

1 Answers

You could use this kind package to autogenerate your slugfield: https://django-autoslug.readthedocs.io/en/latest/fields.html

from django.db import models
from autoslug import AutoSlugField

class MyModel(models.Model):
    title = models.CharField(max_length=200)
    slug = AutoSlugField(populate_from='title')
Related