tortoise / tortoise/tortoise-orm

tortoise.exceptions.OperationalError: the column must appear in the GROUP BY clause or be used in an aggregate function [Postgresql]

Open
#794 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

Model:

class Shop(Model):
    id = fields.BigIntField(pk=True, index=True)
    price = fields.BigIntField()

Code:

async def run():
    await Tortoise.init(db_url=f"postgres://...", modules={"models": ["models"]})
    await Tortoise.generate_schemas()

    for i in range(10):
        await Shop.get_or_create(price=i*1000)

    result = await Shop.all().annotate(price_avg=Avg("price")).first() # tortoise.exceptions.OperationalError: the column "shop.id" must appear in the GROUP BY clause or be used in an aggregate function [Postgresql]
    print(result)
>>> await Shop.all().annotate(price_avg=Avg("price")).sql()
SELECT "id","price",AVG("price") "avg" FROM "shop"

What am I doing wrong?

I understand that the error is due to the fact that the request for work should look like this: SELECT AVG("price") FROM Shop , but I didn't find how it can be normally implemented via orm.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the provided Shop model and the Shop.all().annotate(price_avg=Avg("price")).sql() entry point, reproducing the generated SQL against PostgreSQL. Trace the aggregation query construction and compare it with PostgreSQL's GROUP BY requirement; done means the intended aggregate query has defined behavior and a focused regression test or usage guidance confirms it.

Written by the indexing model from the issue text.

Assessment

Tech stack
postgresql, python
Domain
backend-api-design, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.