Skip to content

Commit e998a19

Browse files
Lordnibblergarrettheel
authored andcommitted
Raise a ValueError if count() is invoked with no hash key AND filters (#313)
1 parent be993ee commit e998a19

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

docs/quickstart.rst

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,18 @@ Alternatively, you can retrieve the table item count by calling the `count` meth
123123
print(UserModel.count())
124124

125125

126+
Note that the first positional argument to `count()` is a `hash_key`. Although
127+
this argument can be `None`, filters must not be used when `hash_key` is `None`:
128+
129+
::
130+
131+
# raises a ValueError
132+
print(UserModel.count(first_name__eq='John'))
133+
134+
# returns count of only the matching users
135+
print(UserModel.count('my_hash_key', first_name__eq='John'))
136+
137+
126138
Batch Operations
127139
^^^^^^^^^^^^^^^^
128140

@@ -156,4 +168,3 @@ Perhaps you want to delete all these users:
156168
items = [UserModel('user-{0}@example.com'.format(x)) for x in range(100)]
157169
for item in items:
158170
batch.delete(item)
159-

pynamodb/models.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -522,9 +522,11 @@ def count(cls,
522522
:param hash_key: The hash key to query. Can be None.
523523
:param consistent_read: If True, a consistent read is performed
524524
:param index_name: If set, then this index is used
525-
:param filters: A dictionary of filters to be used in the query
525+
:param filters: A dictionary of filters to be used in the query. Requires a hash_key to be passed.
526526
"""
527527
if hash_key is None:
528+
if filters:
529+
raise ValueError('A hash_key must be given to use filters')
528530
return cls.describe_table().get(ITEM_COUNT)
529531

530532
cls._get_indexes()

pynamodb/tests/test_model.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1476,6 +1476,10 @@ def fake_dynamodb(*args, **kwargs):
14761476
params = {'TableName': 'UserModel'}
14771477
self.assertEqual(args, params)
14781478

1479+
def test_count_no_hash_key(self):
1480+
with pytest.raises(ValueError):
1481+
UserModel.count(zip_code__le='94117')
1482+
14791483
def test_index_count(self):
14801484
"""
14811485
Model.index.count()

0 commit comments

Comments
 (0)