2014-10-28 09:51:27 +00:00
|
|
|
from django.core.exceptions import ObjectDoesNotExist
|
|
|
|
|
2014-10-01 21:03:16 +00:00
|
|
|
from orchestra.core import services
|
2014-07-18 15:32:27 +00:00
|
|
|
|
|
|
|
|
2015-03-29 16:10:07 +00:00
|
|
|
def get_related_object(origin, max_depth=2):
|
2014-07-18 15:32:27 +00:00
|
|
|
"""
|
|
|
|
Introspects origin object and return the first related service object
|
2021-04-22 12:44:47 +00:00
|
|
|
|
2014-07-18 15:32:27 +00:00
|
|
|
WARNING this is NOT an exhaustive search but a compromise between cost and
|
|
|
|
flexibility. A more comprehensive approach may be considered if
|
|
|
|
a use-case calls for it.
|
|
|
|
"""
|
|
|
|
def related_iterator(node):
|
2016-11-15 09:05:16 +00:00
|
|
|
for field in node._meta.private_fields:
|
2014-07-18 15:32:27 +00:00
|
|
|
if hasattr(field, 'ct_field'):
|
|
|
|
yield getattr(node, field.name)
|
|
|
|
for field in node._meta.fields:
|
2021-04-22 12:44:47 +00:00
|
|
|
if field.remote_field:
|
2014-10-28 09:51:27 +00:00
|
|
|
try:
|
|
|
|
yield getattr(node, field.name)
|
|
|
|
except ObjectDoesNotExist:
|
|
|
|
pass
|
2021-04-22 12:44:47 +00:00
|
|
|
|
2014-07-18 15:32:27 +00:00
|
|
|
# BFS model relation transversal
|
|
|
|
queue = [[origin]]
|
|
|
|
while queue:
|
|
|
|
models = queue.pop(0)
|
|
|
|
if len(models) > max_depth:
|
|
|
|
return None
|
|
|
|
node = models[-1]
|
|
|
|
if len(models) > 1:
|
2014-10-01 21:03:16 +00:00
|
|
|
if type(node) in services:
|
2014-07-18 15:32:27 +00:00
|
|
|
return node
|
|
|
|
for related in related_iterator(node):
|
2014-07-21 15:43:36 +00:00
|
|
|
if related and related not in models:
|
2014-07-18 15:32:27 +00:00
|
|
|
new_models = list(models)
|
|
|
|
new_models.append(related)
|
|
|
|
queue.append(new_models)
|