utils.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import itertools
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.db import transaction
  4. def compile_path_node(ct_id, object_id):
  5. return f'{ct_id}:{object_id}'
  6. def decompile_path_node(repr):
  7. ct_id, object_id = repr.split(':')
  8. return int(ct_id), int(object_id)
  9. def object_to_path_node(obj):
  10. """
  11. Return a representation of an object suitable for inclusion in a CablePath path. Node representation is in the
  12. form <ContentType ID>:<Object ID>.
  13. """
  14. ct = ContentType.objects.get_for_model(obj)
  15. return compile_path_node(ct.pk, obj.pk)
  16. def path_node_to_object(repr):
  17. """
  18. Given the string representation of a path node, return the corresponding instance. If the object no longer
  19. exists, return None.
  20. """
  21. ct_id, object_id = decompile_path_node(repr)
  22. ct = ContentType.objects.get_for_id(ct_id)
  23. return ct.model_class().objects.filter(pk=object_id).first()
  24. def create_cablepath(terminations):
  25. """
  26. Create CablePaths for all paths originating from the specified set of nodes.
  27. :param terminations: Iterable of CableTermination objects
  28. """
  29. from dcim.models import CablePath
  30. cp = CablePath.from_origin(terminations)
  31. if cp:
  32. cp.save()
  33. def rebuild_paths(terminations):
  34. """
  35. Rebuild all CablePaths which traverse the specified nodes.
  36. """
  37. from dcim.models import CablePath
  38. for obj in terminations:
  39. cable_paths = CablePath.objects.filter(_nodes__contains=obj)
  40. with transaction.atomic():
  41. for cp in cable_paths:
  42. cp.delete()
  43. create_cablepath(cp.origins)