[rset] add convenient first() and last() methods on ResultSet
authorDavid Douard <david.douard@logilab.fr>
Thu, 21 Sep 2017 16:29:26 +0200
changeset 12298 08d79eadd1a4
parent 12297 38058ce2a9ec
child 12299 b8eea17fe0b2
[rset] add convenient first() and last() methods on ResultSet These make life easier for the heavy user of the CW shell. Also aliases entities() with all(); so we end with a pretty consistant set: - .one() - .first() - .last() - .all()
cubicweb/rset.py
--- a/cubicweb/rset.py	Tue Apr 24 10:19:42 2018 +0200
+++ b/cubicweb/rset.py	Thu Sep 21 16:29:26 2017 +0200
@@ -393,6 +393,8 @@
             if self.rows[i][col] is not None:
                 yield self.get_entity(i, col)
 
+    all = entities
+
     def iter_rows_with_entities(self):
         """ iterates over rows, and for each row
         eids are converted to plain entities
@@ -459,6 +461,34 @@
         else:
             raise MultipleResultsError("Multiple rows were found for one()")
 
+    def first(self, col=0):
+        """Retrieve the first entity from the query.
+
+        If the result set is empty, raises :exc:`NoResultError`.
+
+        :type col: int
+        :param col: The column localising the entity in the unique row
+
+        :return: the partially initialized `Entity` instance
+        """
+        if len(self) == 0:
+            raise NoResultError("No row was found for first()")
+        return self.get_entity(0, col)
+
+    def last(self, col=0):
+        """Retrieve the last entity from the query.
+
+        If the result set is empty, raises :exc:`NoResultError`.
+
+        :type col: int
+        :param col: The column localising the entity in the unique row
+
+        :return: the partially initialized `Entity` instance
+        """
+        if len(self) == 0:
+            raise NoResultError("No row was found for last()")
+        return self.get_entity(-1, col)
+
     def _make_entity(self, row, col):
         """Instantiate an entity, and store it in the entity cache"""
         # build entity instance