diff --git a/dataset/persistence/table.py b/dataset/persistence/table.py index e8cfeea..34a7412 100644 --- a/dataset/persistence/table.py +++ b/dataset/persistence/table.py @@ -374,12 +374,15 @@ class Table(object): return ResultIter((self.database.executable.execute(q) for q in queries)) def count(self, **_filter): - """ Return the count of results for the given filter set (same filter - options as with ``find()``). """ + """ + Return the count of results for the given filter set (same filter options as with ``find()``). + """ return self.find(return_count=True, **_filter) def __len__(self): - """ Returns the number of rows in the table. """ + """ + Returns the number of rows in the table. + """ return self.count() def distinct(self, *columns, **_filter): @@ -409,6 +412,17 @@ class Table(object): order_by=[c.asc() for c in columns]) return self.database.query(q) + def __getitem__(self, item): + """ This is an alias for distinct which allows the table to be queried as using + square bracket syntax. + :: + # Same as distinct: + print list(table['year']) + """ + if not isinstance(item, tuple): + item = item, + return self.distinct(*item) + def all(self): """ Returns all rows of the table as simple dictionaries. This is simply a shortcut diff --git a/test/test_persistence.py b/test/test_persistence.py index ef570dd..3c1c648 100644 --- a/test/test_persistence.py +++ b/test/test_persistence.py @@ -261,6 +261,14 @@ class TableTestCase(unittest.TestCase): x = list(self.tbl.distinct('place', 'date')) assert len(x) == 6, x + def test_get_items(self): + x = list(self.tbl['place']) + y = list(self.tbl.distinct('place')) + assert x == y, (x, y) + x = list(self.tbl['place', 'date']) + y = list(self.tbl.distinct('place', 'date')) + assert x == y, (x, y) + def test_insert_many(self): data = TEST_DATA * 100 self.tbl.insert_many(data, chunk_size=13)