0

In my resolver, I attempt to aggregate distance driven on rows with a common vehicle id, forcing me to call values('vehicle_id') on the query and thus creating a iterable queryset which throws:
Exception: Received incompatible instance "{'vehicle_id': x, 'sum_distance': y}"
when returned to graphql.

class AssignmentType(DjangoObjectType):
    class Meta:
        model = Assignment

    sum_distance = graphene.Int()

    def resolve_sum_distance(self, info):
        return getattr(self, "sum_distance", None)

class Query(graphene.ObjectType):
    all_assignments = graphene.List(AssignmentType)

    def resolve_all_assignments(self, info, **kwargs):
        return Assignment.objects.order_by().values("vehicle_id").\
            annotate(sum_distance=Sum("distance", output_field=IntegerField()))
       

schema = graphene.Schema(query=Query)

django 4.0.3
graphene 2.19

From the answers I have seen in similar posts like https://stackoverflow.com/a/51425324/7267684, this should not be failing?

Son.Dre
  • 113
  • 2
  • 9
  • The `AssignmentType` expects an object of the type `Assignment`, but received the group by result. – JPG Mar 29 '22 at 11:55
  • @JPG Do you know of a general solution to this problem without creating new types? – Son.Dre Mar 29 '22 at 12:03
  • https://github.com/graphql-python/graphene-django/issues/787 seems to address the same issue, only instead using a connection field. Graphene was presumably fixed to handle this but I have had no luck with it. – Son.Dre Mar 29 '22 at 12:06

1 Answers1

0

Try This Once Not Sure

from django.db.models import IntegerField, Sum, Value
from django.db.models.functions import Coalesce
    
    
class AssignmentType(DjangoObjectType):
    class Meta:
        model = Assignment

    sum_distance = graphene.Int()

    def resolve_sum_distance(self, info):
        return getattr(self, "sum_distance", 0)

class Query(graphene.ObjectType):
    all_assignments = graphene.List(AssignmentType)

    def resolve_all_assignments(self, info, **kwargs):
        return  Assignment.objects.order_by().values("vehicle_id")annotate(sum_distance=Coalesce(Sum("distance", output_field=IntegerField()), Value(0)))