utils.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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.
  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.get(pk=object_id)
  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)