[Categories] use categories from Django ORM
[mygpo.git] / mygpo / directory / management / commands / category-merge-spellings.py
blobdcc1a188075425c134a732052dcd216e1de4274d
1 from datetime import datetime
3 from django.core.management.base import BaseCommand
4 from django.utils.text import slugify
6 from mygpo.directory.models import Category, CategoryTag
9 class Command(BaseCommand):
11 def handle(self, *args, **options):
13 if len(args) < 2:
14 print """
15 Merges multiple categories into one by listing them as alternative spellings
17 Usage:
18 ./manage.py category-merge-spellings <category> <spelling1> [<spelling2> ...]
19 """
20 return
22 start_time = datetime.utcnow()
23 cat_name = args[0]
24 spellings = args[1:]
26 print "Adding new spellings for %s ..." % cat_name
27 category, created = Category.objects.get_or_create(
28 tags__tag=slugify(cat_name),
29 defaults={
30 'title': cat_name,
34 for spelling in spellings:
36 tag, created = CategoryTag.objects.get_or_create(
37 tag=spelling,
38 defaults={
39 'category': category,
43 if created:
44 # we just created a new tag-assignedment -- nothing else to do
45 continue
47 oldcategory = tag.category
49 for entry in oldcategory.entries:
50 # todo: this might cause a constraint violation if the
51 # podcast is already a entry of the new category
52 entry.category = category
53 entry.save()
55 tag.category = category
56 tag.save()