tortoise/tortoise-orm

Provide count() in Model

lnxsr opened this issue · 1 comments

Is your feature request related to a problem? Please describe.
It took me quite some time as newbie to figure out how to get the count of all rows in a table.

Describe the solution you'd like
An easy way to get the count of rows of a table.

Provide count() in Model similar like this

@classmethod
async def count(cls):
    return (await cls.first().annotate(count=Count(<some column>)).count

Describe alternatives you've considered
The current workaround I ended up with is

class Counter:
    @classmethod
    async def count(cls):
        return (await cls.first().annotate(count=Count(next(iter(cls._meta.db_fields))))).count

class Tournament(Counter, Model):
    pass

Additional context
Maybe PK should be preferred if existing, with a fallback.

@lnxsr there's count method on QuerySet, see https://tortoise.github.io/query.html?h=count#tortoise.queryset.QuerySet.count

print(await Tournament.all().count())