Make __getitem__ an alias for distinct(). Fixes #87.

This commit is contained in:
Friedrich Lindenberg 2015-05-23 13:01:36 +02:00
parent 5e5d69457e
commit 819c37d61d
2 changed files with 25 additions and 3 deletions

View File

@ -374,12 +374,15 @@ class Table(object):
return ResultIter((self.database.executable.execute(q) for q in queries)) return ResultIter((self.database.executable.execute(q) for q in queries))
def count(self, **_filter): 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) return self.find(return_count=True, **_filter)
def __len__(self): def __len__(self):
""" Returns the number of rows in the table. """ """
Returns the number of rows in the table.
"""
return self.count() return self.count()
def distinct(self, *columns, **_filter): def distinct(self, *columns, **_filter):
@ -409,6 +412,17 @@ class Table(object):
order_by=[c.asc() for c in columns]) order_by=[c.asc() for c in columns])
return self.database.query(q) 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): def all(self):
""" """
Returns all rows of the table as simple dictionaries. This is simply a shortcut Returns all rows of the table as simple dictionaries. This is simply a shortcut

View File

@ -261,6 +261,14 @@ class TableTestCase(unittest.TestCase):
x = list(self.tbl.distinct('place', 'date')) x = list(self.tbl.distinct('place', 'date'))
assert len(x) == 6, x 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): def test_insert_many(self):
data = TEST_DATA * 100 data = TEST_DATA * 100
self.tbl.insert_many(data, chunk_size=13) self.tbl.insert_many(data, chunk_size=13)