commit to CouchDB only when necessary
[mygpo.git] / mygpo / directory / management / commands / category-merge-spellings.py
blobd3b0c390b8b6c06be0286887d675992a9601675a
1 from datetime import datetime
3 from django.core.management.base import BaseCommand
5 from mygpo.directory.models import Category
6 from mygpo.data.models import DirectoryEntry
7 from mygpo.migrate import use_couchdb
10 class Command(BaseCommand):
12 @use_couchdb()
13 def handle(self, *args, **options):
15 if len(args) < 2:
16 print """
17 Merges multiple categories into one by listing them as alternative spellings
19 Usage:
20 ./manage.py category-merge-spellings <category> <spelling1> [<spelling2> ...]
21 """
22 return
24 start_time = datetime.utcnow()
25 cat_name = args[0]
26 spellings = args[1:]
28 print "Adding new spellings for %s ..." % cat_name
29 category = Category.for_tag(cat_name)
31 if not category:
32 print " creating new category %s" % cat_name
33 category = Category()
34 category.label = cat_name
36 for spelling in spellings:
37 new_cat = Category.for_tag(spelling)
39 if spelling == cat_name or (spelling in category.spellings):
40 print " skipped %s: already in category" % spelling
41 continue
43 if not new_cat:
44 #merged category doesn't yet exist
45 category.spellings.append(spelling)
47 elif new_cat and category._id == new_cat._id:
48 print " set %s as new label" % cat_name
49 category.spellings = list(set([x for x in category.spellings + [category.label] if x != cat_name]))
50 category.label = cat_name
52 else:
53 print " add spelling %s" % spelling
54 category.spellings = list(set(category.spellings + [new_cat.label] + new_cat.spellings))
55 category.weight += new_cat.weight
56 new_cat.delete()
58 category.updated = start_time
59 category.save()