Conversion script

shacker edited this page May 18, 2011 · 1 revision
Clone this wiki locally
"""
If you previously ran django-taggit in default mode and mixed-case tags
have crept into your database (with slugs ending in _1), this script will
remove them, re-entering them with lowercase equivalents. It will also
lowercase all tags that had upper-case characters even if they weren't
duplicates.
"""

#################### Set up Django environment
import sys,os

sys.path.append('.')
sys.path.append('../')
sys.path.append('../lib/python2.6/site-packages/django')

os.environ['DJANGO_SETTINGS_MODULE'] ='bucketlist.settings'

from django.core.management import setup_environ
from bucketlist import settings
from taggit.models import Tag, TaggedItem
from bucket.models import Item
from django.template.defaultfilters import lower
setup_environ(settings)


#################### Import models from Django project and custom vars

from bucket.models import *
from django.contrib.auth.models import User, Group

#################### Start work

# Find all tags that have slugs ending in '_1'
badtags = Tag.objects.filter(slug__icontains='_1')

# For each element in badtags, find the corresponding tag without _1
goodtags = []
for b in badtags:
    print b

    goodslug = b.slug.replace('_1','')
    print goodslug

    goodtag = Tag.objects.get(slug=goodslug)
    print goodtag

    # Now find all of the TaggedItems that have the bad tag.
    items = TaggedItem.objects.filter(tag=b)
    for i in items:
        print i
        # Retrieve the goal that this TaggedItem is for
        try:
            goal = Item.objects.get(id=i.object_id)
            print goal
            # Remove the bad tag
            goal.tags.remove(b)
            # Add the good tag if it doesn't have it already
            goal.tags.add(goodtag)
        except:
            pass
    # Now delete the bad tag completely
    b.delete()

    print

# Just in case, make sure there are no tags with uppercase characters
alltags = Tag.objects.all()
for t in alltags:
    if t.name != lower(t.name):
        print "lowercasing tag " + t.name
        t.name = lower(t.name)
        t.save()