Combine DjangoObjectType with ObjectType - Django, GraphQL

Viewed 369

I'm trying to combine DjangoType with ObjectType.

I have models:


class Scenario(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=50)

class Result(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    scenario = models.ForeignKey(
        'optimiser.Scenario',
        on_delete=models.CASCADE,
        related_name='result'
    )
    data = JSONField()

What I'm trying to do is to query scenario with foreign key of result model

In my schema I have:

class JsonClass(ObjectType):
    key = graphene.String()
    header = graphene.String()

class Result(ObjectType):
    id = graphene.Int()
    data = graphene.Field(JsonClass)  

class ScenarioJson(ObjectType):
   key = graphene.String()
   value = graphene.String()

class ScenarioData(ObjectType):
    id = graphene.Int()
    name = graphene.String()
    data = graphene.Field(ScenarioJson)
    result = graphene.Field(Result)

To test how it works with DjangoObjectType I'm getting all Result so I wanna implement that into ObjectType

class ScenarioType(DjangoObjectType):
    class Meta:
        model = Scenario

And my Query:

class Query:
     scenario = graphene.Field(ScenarioData, id=graphene.Int()) 
     def resolve_scenario(self, info, **kwargs): 
        return Scenario.objects.get(id=kwargs.get('id'))

So basically what I'm getting is:

query {
    scenario(id: 100) {
     id, // 100
     name, // Scenario1
     data: {
         key, // scenario key1
         value // value key1
     },
     result {
       id // null
       data // null
     }
    }
}

When I'm using ScenarioType with DjangoObjectType I'm getting all results but I cannot query JSON

query {
    scenario(id: 100) {
     id, // 100
     name, // Scenario1
     data: "{'key' : 'scenario key1', ..}" // string 
     result {
       id // 12
       data // "{'key1': 'ke2'}"
     }
    }
}

So I was wondering how to implement DjangoObjectType inside ObjectType?

1 Answers
Related