"""This command manages Closure Tables implementation It adds new levels and cleans links between Educatives. This way, it's relatively easy to fetch an entire tree with just one tiny request. """ from django.core.management.base import BaseCommand from ultron.objective.models import Educative, PrerequisiteClosure class Command(BaseCommand): def handle(self, *args, **options): educative_list = Educative.objects.all() count = 0 for educative in educative_list: updated = False max_level = 0 max_rank = 0 count += 1 print(str(count) + ' - Traitement de ' + str(educative.long_label)) breadcrumb = educative.breadcrumb() for path in range(0, len(breadcrumb)): tree = set(PrerequisiteClosure.objects.filter(descendant=educative, path=path)) for position, ancestor in enumerate(breadcrumb[path]): tree_path, _ = PrerequisiteClosure.objects.get_or_create( ancestor=ancestor, descendant=educative, level=position, path=path ) max_level = max(max_level, position) max_rank = max(max_rank, ancestor.rank + 1) if tree_path in tree: tree.remove(tree_path) for tree_path in tree: tree_path.delete() # Dans une condition pour espérer accélérer le traitement if educative.level != max_level: updated = True educative.level = max_level if educative.rank != max_rank: updated = True educative.rank = max_rank if updated: educative.save()