rename/move filters, validate_doc_update
[mygpo.git] / mygpo / directory / management / commands / category-merge-spellings.py
blob035a36895a5193804ddf973c88ea2c16521ee500
1 from datetime import datetime
3 from django.core.management.base import BaseCommand
5 from mygpo.directory.models import Category
8 class Command(BaseCommand):
10 def handle(self, *args, **options):
12 if len(args) < 2:
13 print """
14 Merges multiple categories into one by listing them as alternative spellings
16 Usage:
17 ./manage.py category-merge-spellings <category> <spelling1> [<spelling2> ...]
18 """
19 return
21 start_time = datetime.utcnow()
22 cat_name = args[0]
23 spellings = args[1:]
25 print "Adding new spellings for %s ..." % cat_name
26 category = Category.for_tag(cat_name)
28 if not category:
29 print " creating new category %s" % cat_name
30 category = Category()
31 category.label = cat_name
33 for spelling in spellings:
34 new_cat = Category.for_tag(spelling)
36 if spelling == cat_name or (spelling in category.spellings):
37 print " skipped %s: already in category" % spelling
38 continue
40 if not new_cat:
41 #merged category doesn't yet exist
42 category.spellings.append(spelling)
44 elif new_cat and category._id == new_cat._id:
45 print " set %s as new label" % cat_name
46 category.spellings = list(set([x for x in category.spellings + [category.label] if x != cat_name]))
47 category.label = cat_name
49 else:
50 print " add spelling %s" % spelling
51 category.spellings = list(set(category.spellings + [new_cat.label] + new_cat.spellings))
52 category.merge_podcasts(new_cat.podcasts)
53 new_cat.delete()
55 category.updated = start_time
56 category.save()