allow to link to multiple entities stable
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Wed, 14 Oct 2009 16:30:46 +0200
branchstable
changeset 3670 b7ec030a5e10
parent 3669 4eb33ee29c84
child 3671 c765adac7f5c
allow to link to multiple entities
__init__.py
test/unittest_entity.py
--- a/__init__.py	Wed Oct 14 15:59:00 2009 +0200
+++ b/__init__.py	Wed Oct 14 16:30:46 2009 +0200
@@ -136,7 +136,14 @@
         relations = []
         restrictions = set()
         cachekey = []
+        pending_relations = []
         for attr, value in kwargs.iteritems():
+            if isinstance(value, (tuple, list, set, frozenset)):
+                if len(value) == 1:
+                    value = iter(value).next()
+                else:
+                    pending_relations.append( (attr, value) )
+                    continue
             if hasattr(value, 'eid'): # non final relation
                 rvar = attr.upper()
                 # XXX safer detection of object relation
@@ -155,7 +162,16 @@
             rql = '%s: %s' % (rql, ', '.join(relations))
         if restrictions:
             rql = '%s WHERE %s' % (rql, ', '.join(restrictions))
-        return self.execute(rql, kwargs, cachekey).get_entity(0, 0)
+        created = self.execute(rql, kwargs, cachekey).get_entity(0, 0)
+        for attr, values in pending_relations:
+            if attr.startswith('reverse_'):
+                restr = 'Y %s X' % attr[len('reverse_'):]
+            else:
+                restr = 'X %s Y' % attr
+            self.execute('SET %s WHERE X eid %%(x)s, Y eid IN (%s)' % (
+                restr, ','.join(str(r.eid) for r in values)),
+                         {'x': created.eid}, 'x')
+        return created
 
     # url generation methods ##################################################
 
--- a/test/unittest_entity.py	Wed Oct 14 15:59:00 2009 +0200
+++ b/test/unittest_entity.py	Wed Oct 14 16:30:46 2009 +0200
@@ -470,17 +470,19 @@
 
     def test_create_entity(self):
         p1 = self.add_entity('Personne', nom=u'fayolle', prenom=u'alexandre')
+        p2 = self.add_entity('Personne', nom=u'campeas', prenom=u'aurelien')
         note = self.add_entity('Note', type=u'z')
         req = self.request()
         p = req.create_entity('Personne', nom=u'di mascio', prenom=u'adrien',
-                              connait=p1, evaluee=p1,
+                              connait=p1, evaluee=[p1, p2],
                               reverse_ecrit_par=note)
         self.assertEquals(p.nom, 'di mascio')
         self.assertEquals([c.nom for c in p.connait], ['fayolle'])
-        self.assertEquals([c.nom for c in p.evaluee], ['fayolle'])
+        self.assertEquals(sorted([c.nom for c in p.evaluee]), ['campeas', 'fayolle'])
         self.assertEquals([c.type for c in p.reverse_ecrit_par], ['z'])
 
 
+
 if __name__ == '__main__':
     from logilab.common.testlib import unittest_main
     unittest_main()