How to get all columns in a table by apply group on couple of fields in django ORM

Hi All,

I’ve 2 tables with below fields

Attribute table:

fields: attribute_name, total, city _id, year, month

city table:

fields: id, city_name, state

and I want to perform group by on state and attribute_name and return all columns in attribute table.

please help me how to solve

Thanks in advance

Here’s a similar example i have done in the past.

It does the group by for the month, year fields (that was annotated, but it does not need to be) on the first values call, after that, you use annotate or aggreate on your qs, lastly order it


from django.db.models import Count, Sum

qs = SomeModel.objects.filter(some_filter="foo")
values = (
        qs.annotate(month=Month("last_updated_at"), year=Year("last_updated_at"))
        .values("month", "year")
        .annotate(
            total_deliveries=Count("id"),
            customer_price_amount=Sum("price"),
            payment_fee_amount=Sum("payment_method_charged_fee_amount"),
            earned_amount=Sum("commercial_price"),
            franchisee_amount=Sum("franchisee_split"),
            company_amount=Sum("company_split"),
        )
        .order_by("-month")
    )

Thank you for the response, It will group by month, year but as per my requirement It should group on attribute name and state and fetch_all fields in Attribute table, I will take reference of your code and will try