0

Assuming I have a Django model with a number of relationships that are related, is it possible to nest them through a non-model type for querying purposes? A specific example:

Assume I have a model Organization with relationships that include X_projects, X_accounts, etc which are also Django models.

It is pretty easy to allow queries like:

query fetchOrganization($id: Int!) {
  organization(id: $id) {
    id,
    ... other fields ...
    X_accounts {
      ...
    }
    X_projects {
      ...
    }
  }
}

but I would prefer to support queries like:

query fetchOrganization($id: Int!) {
  organization(id: $id) {
    id,
    ... other fields ...
    X {
      accounts {
        ...
      }
      projects {
        ...
      }
    }
  }
}

Given that X doesn't actually make sense to be a Django model / relation on the backend, is there a way to achieve this?

Matt Sanders
  • 8,023
  • 3
  • 37
  • 49
  • https://docs.graphene-python.org/projects/django/en/latest/queries/#plain-objecttypes ? – xadm Nov 02 '20 at 21:23

1 Answers1

1

Yes, you can do this by modifying a new resolver for "X" that uses a custom object type that has fields for accounts and projects.

You'll need to create a new composite object type that is a container for accounts and projects, for example (assuming that you've also defined a DjangoObjectType class already for your account and project models)

class XType(graphene.ObjectType):
    account = graphene.Field(AccountType)
    project = graphene.Field(ProjectType)

Then modify your Organization type definition to add the new field, something like

class OrganizationType(DjangoObjectType):
   x = graphene.Field(XType)

   class Meta:
        model = Organization
        # You might want to exclude the x_project and x_account fields

   def resolve_x(self, info, **kwargs):
       # You'll have to work out how to parse arguments and fetch account and project
       return XType(account=account, project=project)
Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99