peewee.ProgrammingError: column must appear in the GROUP BY clause or be used in an aggregate function

492 Views Asked by At

I am trying to write a query in Peewee with a PostgreSQL backend to return the top product exported by each state based on the export_value for a given product-state pair. Here is the query I have right now:

    subquery = (
        models.Trade.select(
            models.Trade.state.alias('state_1'),
            models.Trade.product.alias('product_1'),
            fn.SUM(models.Trade.export_value).alias("export_value_1")
        ).where(
            models.Trade.origin_country == origin_country,
            models.Trade.year == year
        ).group_by(
            models.Trade.state,
            models.Trade.product
        ).alias("subquery")
    )

    query = (
        models.Trade.select(
            models.Trade.state,
            models.Trade.product,
            fn.MAX(subquery.c.export_value_1).alias("export_value")
        ).join(
            subquery, on=(
                (models.Trade.state == subquery.c.state_1) &
                (models.Trade.product == subquery.c.product_1)
            )
        ).group_by(
            models.Trade.state
        )
    )

I am getting an error running this query because I am not using the models.Trade.product in a GROUP BY or aggregator. I am new to Peewee and would like any tips on how I can accomplish what I want either by modifying this query or through a different query.

0

There are 0 best solutions below