From fc9c91b7fa945f9e6ac6def8553e4d701fbdbfb1 Mon Sep 17 00:00:00 2001
From: Timm Fitschen <t.fitschen@indiscale.com>
Date: Wed, 13 May 2020 14:25:41 +0200
Subject: [PATCH] BUG: get_parent(entity) fall-back to search by name

---
 src/caosdb/common/models.py |  9 ++++++---
 unittests/test_record.py    | 16 +++++++++++++++-
 2 files changed, 21 insertions(+), 4 deletions(-)

diff --git a/src/caosdb/common/models.py b/src/caosdb/common/models.py
index ecd74551..343b0bbb 100644
--- a/src/caosdb/common/models.py
+++ b/src/caosdb/common/models.py
@@ -519,9 +519,12 @@ class Entity(object):
                     return p
         elif isinstance(key, Entity):
             if key.id is not None:
-                return self.get_parent(int(key.id))
-            else:
-                return self.get_parent(key.name)
+                # first try by id
+                found = self.get_parent(int(key.id))
+                if found is not None:
+                    return found
+            # otherwise by name
+            return self.get_parent(key.name)
         else:
             for p in self.parents:
                 if (p.name is not None
diff --git a/unittests/test_record.py b/unittests/test_record.py
index d0acb235..850e9c69 100644
--- a/unittests/test_record.py
+++ b/unittests/test_record.py
@@ -24,7 +24,7 @@
 #
 """Tests for the Record class."""
 # pylint: disable=missing-docstring
-from caosdb import Entity, Record
+from caosdb import Entity, Record, RecordType
 
 
 def test_is_entity():
@@ -59,3 +59,17 @@ def test_get_parent_by_id():
     rec.add_parent(234)
     assert rec.get_parent(None) is None
     assert rec.get_parent(234) is not None
+
+def test_get_parent_by_entity():
+    rec = Record(id="123")
+    rt = RecordType("Test", id=234)
+    rec.add_parent(rt)
+    assert rec.get_parent(rt) is not None
+
+    rec = Record()
+    rec.add_parent(234)
+    assert rec.get_parent(rt) is not None
+
+    rec = Record()
+    rec.add_parent("Test")
+    assert rec.get_parent(rt) is not None
-- 
GitLab