Skip to content

Commit

Permalink
Fixed .count() when a join happens (#109) (#118)
Browse files Browse the repository at this point in the history
Fixes #109
  • Loading branch information
grigi authored Apr 1, 2019
1 parent b75bd0e commit 9661ae3
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 5 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
Changelog
=========

0.11.8
------
- Fixed ``.count()`` when a join happens (#109)


0.11.7
------
- Fixed 'unique_together' for foreign keys (#114)
Expand Down
2 changes: 1 addition & 1 deletion tortoise/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,4 +392,4 @@ async def do_stuff():
loop.run_until_complete(Tortoise.close_connections())


__version__ = "0.11.7"
__version__ = "0.11.8"
3 changes: 1 addition & 2 deletions tortoise/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,15 +518,14 @@ class CountQuery(AwaitableQuery):
def __init__(self, model, db, q_objects, annotations, custom_filters
) -> None:
super().__init__(model, db)
table = Table(model._meta.table)
self.query = model._meta.basequery
self.resolve_filters(
model=model,
q_objects=q_objects,
annotations=annotations,
custom_filters=custom_filters,
)
self.query = self.query.select(Count(table.star))
self.query = self.query.select(Count("*"))

async def _execute(self):
result = await self._db.execute_query(str(self.query))
Expand Down
10 changes: 8 additions & 2 deletions tortoise/tests/test_queryset.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from tortoise.contrib import test
from tortoise.exceptions import DoesNotExist, MultipleObjectsReturned
from tortoise.tests.testmodels import IntFields
from tortoise.tests.testmodels import IntFields, MinRelation, Tournament

# TODO: Test the many exceptions in QuerySet
# TODO: .filter(intnum_null=None) does not work as expected
Expand All @@ -14,9 +14,15 @@ async def setUp(self):

async def test_all_count(self):
self.assertEqual(await IntFields.all().count(), 30)

self.assertEqual(await IntFields.filter(intnum_null=80).count(), 0)

async def test_join_count(self):
tour = await Tournament.create(name="moo")
await MinRelation.create(tournament=tour)

self.assertEqual(await MinRelation.all().count(), 1)
self.assertEqual(await MinRelation.filter(tournament__id=tour.id).count(), 1)

async def test_modify_dataset(self):
# Modify dataset
await IntFields.filter(intnum__gte=70).update(intnum_null=80)
Expand Down

0 comments on commit 9661ae3

Please sign in to comment.