2

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
  • 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 Commented Aug 27, 2022 at 7:01

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.