Skip to content

Instantly share code, notes, and snippets.

@aliceridgway
Created June 4, 2022 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliceridgway/4af16fe3b45c498bcb964c6392159e8a to your computer and use it in GitHub Desktop.
Save aliceridgway/4af16fe3b45c498bcb964c6392159e8a to your computer and use it in GitHub Desktop.
# Generated by Django 4.0.5 on 2022-06-04 18:08
import autoslug.fields
from django.db import migrations
from django.utils.text import slugify
DEFAULT = "abc"
def forwards(apps, _):
Movie = apps.get_model("movies", "Movie")
movies = Movie.objects.all()
for movie in movies:
movie.slug = slugify(movie.title)
movie.save()
def backwards(apps, _):
Movie = apps.get_model("movies", "Movie")
movies = Movie.objects.all()
for movie in movies:
movie.slug = DEFAULT
movie.save()
class Migration(migrations.Migration):
dependencies = [
('movies', '0003_alter_movie_popularity'),
]
operations = [
migrations.AddField(
model_name='movie',
name='slug',
field=autoslug.fields.AutoSlugField(
always_update=True, default=DEFAULT, editable=True, populate_from='title'),
preserve_default=False,
),
migrations.RunPython(forwards, backwards)
]
@aliceridgway
Copy link
Author

Migration created for this tutorial about adding a non-nullable field to a Django model. https://ctrlzblog.com/django-migrations-how-to-add-non-nullable-fields-without-compromising-your-database/

The migration adds a slug field to a model called Movie and then runs a function that will iterate through the existing movies and assign it with a slug generated from the title.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment