Skip to content

Instantly share code, notes, and snippets.

@darwing1210
Created February 11, 2017 17:05
Show Gist options
  • Save darwing1210/c0bfd7211704cf71c2e8137b022a080d to your computer and use it in GitHub Desktop.
Save darwing1210/c0bfd7211704cf71c2e8137b022a080d to your computer and use it in GitHub Desktop.
Example migraton file to autogerate slug from existing django models
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2017-02-11 16:54
from __future__ import unicode_literals
from django.db import migrations, models
from django.template.defaultfilters import slugify
def migrate_docs_forward(apps, schema_editor):
documents = apps.get_model("documents", "Documents")
for instance in documents.objects.all():
print ("Generating slug for %s" % instance.name)
instance.slug = slugify("%s" % instance.name)
instance.save() # Will trigger slug update
def migrate_docs_backards(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('documents', '0005_auto_20170211_1628'),
]
operations = [
migrations.AddField(
model_name='documents',
name='slug',
field=models.SlugField(blank=True, help_text='Short descriptive unique name for use in urls.', max_length=200, unique=True, verbose_name='Slug'),
),
migrations.RunPython(
migrate_docs_forward,
migrate_docs_backards,
),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment