rset.py
changeset 9347 bd841d6ae723
parent 9331 c6f54ed6b60a
child 9780 8e687be43d84
--- a/rset.py	Tue Dec 10 12:36:50 2013 +0100
+++ b/rset.py	Wed Dec 11 17:52:54 2013 +0100
@@ -23,7 +23,7 @@
 
 from rql import nodes, stmts
 
-from cubicweb import NotAnEntity
+from cubicweb import NotAnEntity, NoResultError, MultipleResultsError
 
 
 class ResultSet(object):
@@ -437,6 +437,25 @@
             raise NotAnEntity(etype)
         return self._build_entity(row, col)
 
+    def one(self, col=0):
+        """Retrieve exactly one entity from the query.
+
+        If the result set is empty, raises :exc:`NoResultError`.
+        If the result set has more than one row, raises
+        :exc:`MultipleResultsError`.
+
+        :type col: int
+        :param col: The column localising the entity in the unique row
+
+        :return: the partially initialized `Entity` instance
+        """
+        if len(self) == 1:
+            return self.get_entity(0, col)
+        elif len(self) == 0:
+            raise NoResultError("No row was found for one()")
+        else:
+            raise MultipleResultsError("Multiple rows were found for one()")
+
     def _build_entity(self, row, col):
         """internal method to get a single entity, returns a partially
         initialized Entity instance.