utils.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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.
  18. """
  19. ct_id, object_id = decompile_path_node(repr)
  20. ct = ContentType.objects.get_for_id(ct_id)
  21. return ct.model_class().objects.get(pk=object_id)
  22. def create_cablepath(node):
  23. """
  24. Create CablePaths for all paths originating from the specified node.
  25. """
  26. from dcim.models import CablePath
  27. cp = CablePath.from_origin(node)
  28. if cp:
  29. cp.save()
  30. def rebuild_paths(obj):
  31. """
  32. Rebuild all CablePaths which traverse the specified node
  33. """
  34. from dcim.models import CablePath
  35. cable_paths = CablePath.objects.filter(path__contains=obj)
  36. with transaction.atomic():
  37. for cp in cable_paths:
  38. cp.delete()
  39. if cp.origin:
  40. create_cablepath(cp.origin)