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?
-
Simply write a single method where the objects must be created, so that there will be one and only entry point to create an instance, and modify the slug field as you wishë..– ë..2022-08-27 07:01:26 +00:00Commented Aug 27, 2022 at 7:01
Add a comment
|
1 Answer
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')
1 Comment
todel23
Great! This seems working this case, but is there something more flexible? I mean can I populate some field based on other(s) in more generic way? Like I want to add field
full_name which is f'{first_name} {last_name}', I understand the example is meaningless, but it shows what I really want.