Ultron/ultron/objective/management/commands/rebuild_tree.py

45 lines
1.9 KiB
Python

"""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()
educative_list = [Educative.objects.get(pk=44)]
for educative in educative_list:
# print('__________________________________________________________________________')
# print('Traitement de ' + str(educative))
# breadcrumb = [node for node in educative.breadcrumb()]
breadcrumb = educative.breadcrumb()
for path in range(0, len(breadcrumb)):
# print(' ˪ ' + str(path + 1) + 'ème chemin')
tree = set(PrerequisiteClosure.objects.filter(descendant=educative, path=path))
# print(' ' + str(tree))
for position, ancestor in enumerate(breadcrumb[path]):
# print(' ˪ Traitement de ' + str(ancestor.long_label) + ' : ' + str(ancestor.long_label) + ' -> ' + str(educative.long_label) + ' | ' + str(position) + ' | ' + str(path))
tree_path, _ = PrerequisiteClosure.objects.get_or_create(
ancestor=ancestor, descendant=educative, level=position, path=path
)
# if _:
# print(' -> CREATION : ' + str(tree_path))
# else:
# print(' -> RECUPERATION : ' + str(tree_path))
if tree_path in tree:
tree.remove(tree_path)
for tree_path in tree:
# print(' DELETE : ' + str(tree_path))
tree_path.delete()