utils.py 826 B

12345678910111213141516171819202122232425262728
  1. from django.contrib.contenttypes.models import ContentType
  2. def compile_path_node(ct_id, object_id):
  3. return f'{ct_id}:{object_id}'
  4. def decompile_path_node(repr):
  5. ct_id, object_id = repr.split(':')
  6. return int(ct_id), int(object_id)
  7. def object_to_path_node(obj):
  8. """
  9. Return a representation of an object suitable for inclusion in a CablePath path. Node representation is in the
  10. form <ContentType ID>:<Object ID>.
  11. """
  12. ct = ContentType.objects.get_for_model(obj)
  13. return compile_path_node(ct.pk, obj.pk)
  14. def path_node_to_object(repr):
  15. """
  16. Given the string representation of a path node, return the corresponding instance.
  17. """
  18. ct_id, object_id = decompile_path_node(repr)
  19. ct = ContentType.objects.get_for_id(ct_id)
  20. return ct.model_class().objects.get(pk=object_id)