Created
June 4, 2022 19:50
-
-
Save aliceridgway/4af16fe3b45c498bcb964c6392159e8a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.