3

I'd like to be able to write a query that looks like this, using a human primary key rather than the opaque relay IDs:

query {
    issue(pk: 10) {
        pk
        state
    }
}

I've been able to add the int pk field from the model; however, I haven't been able to figure out how to query it (and I'm a little confused about how I'd switch to a custom filterset for this).

from django.db import models
import graphene
from graphene import relay

class Issues(models.Model):
    state = models.CharField(default='')
    text = models.TextField(default='')

class IssueNode(DjangoObjectType):
   pk = graphene.Int(source='pk')
   class Meta:
       model = Issue
       interfaces = (relay.Node,)
       filter_fields = ['pk', 'state']

class Query(graphene.ObjectType):
    issue = relay.Node.Field(IssueNode)
    issues = DjangoFilterConnectionField(IssueNode)

This will raise an error about pk:

TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: pk

With this set up, I can write a query that looks like:

query {
    issue(id: 'ascadf2e31af=') {
        state
    }
}

but since the application previously used human readable IDs, I'd like to support that as well.

Any ideas on how to set up a custom filterset or if there's a native way to do this with graphene-django?

Jeff Tratner
  • 16,270
  • 4
  • 47
  • 67

1 Answers1

0

You might just want to use the default graphene.Field and add it to your code like so:

import graphene

from django.shortcuts import get_object_or_404


class Query(graphene.ObjectType):
   issue_by_pk = Field(IssueNode, pk=graphene.Int())

   def resolve_issue_by_pk(parent, info, **kwargs):
      pk = kwargs.get('pk')
      return get_object_or_404(models.Issue, pk=pk)


Your graphQL query

query findIssue {
   issueByPk(pk:1){
      id # will return relay id
   }
}

Let me know if this works for you.

matty
  • 13
  • 4