GraphQL with Aggregates

1.4k views Asked by At

I have one Django model called Product with fields name, spec, sub_group and a FK to self called class

I need to use GraphQL to query several aggregates -

  1. Product.objects.values('sub_group').annotate(group_count=Count('sub_group'))

  2. Product.objects.select_related('class').values('class__name', 'class__spec').annotate(class_count=Count('class'))

I am experimenting with schemas but not going anywhere

from django.db.models import Count
from graphene import Schema, ObjectType, String, Int, List

from products.models import Product
class ProductNode(ObjectType):
    class__name = String()
    class__spec = String()
    class_count = Int()
    group_count = Int()


class Query(ObjectType):
    all_classes = List(ProductNode)
    all_groups = List(ProductNode)

    def resolve_all_classes(self, args, context, info):
        return Product.objects.values('sub_group').annotate(group_count=Count('sub_group'))

    def resolve_all_groups(self, args, context, info):
        return Product.objects.select_related('class').values(
            'class__name', 'classification__spec').exclude(
            class__name='').annotate(
            class_count=Count('class'))


schema = Schema(query=Query)

Need help to fix this as I dont see any examples using aggregation queries.

0

There are 0 answers