tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.39k stars 359 forks source link

Missing group by clause in SQL query while trying to count grouped and filtered objects. #1503

Open arrenanv opened 8 months ago

arrenanv commented 8 months ago

Describe the bug I want to know user position to form top of players. So when I'm trying to use this code (count how many users have won more games than specified one, 10 - is the number of wins specified player has): await Games.filter(is_active=False).group_by('winner_id').annotate(wins=Count('winner_id')).filter(wins__gt=10).count() this query is produced: SELECT COUNT(*) FROM "games" WHERE "is_active"=false HAVING COUNT("winner_id")>10 but here is missing GROUP BY clause, that's why invalid output is given.

To Reproduce

class Games(Model):
    id = fields.IntField(pk=True, index=True)

    winner: fields.ForeignKeyNullableRelation[Users] = fields.ForeignKeyField(
        'models.Users', related_name='games_won', null=True
    )

    is_active = fields.BooleanField(default=True)

    class Meta:
        table = 'games'

await Games.filter(is_active=False).group_by('winner_id').annotate(wins=Count('winner_id')).filter(wins__gt=10).count()

Expected behavior Query to count how many objects there are after grouping by and filtering through annotated field.