utils.py 1.6 KB

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