通过graphene-django中的主键查找(带有中继)

时间:2019-05-02 08:54:01

标签: django graphql graphene-python graphene-django

我希望能够使用人工主键而不是不透明的中继ID编写如下所示的查询:

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

我已经能够从模型中添加int pk字段;但是,我一直无法弄清楚如何查询(对此我有些困惑,我该如何切换到自定义过滤器集)。

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)

这将引发关于pk的错误:

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

通过此设置,我可以编写如下查询:

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

但是由于该应用程序以前使用的是人类可读的ID,所以我也希望支持它。

关于如何设置自定义过滤器集的任何想法,或者是否有使用石墨烯-django的本机方法?

1 个答案:

答案 0 :(得分:0)

您可能只想使用默认的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) 并将其添加到代码中,如下所示:

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

您的graphQL查询

docker run   --net=host   --rm <kafka docker > kafka-consumer-groups --zookeeper localhost:32181  --delete --group consumer1
Delete for group consumer1 failed because its consumers are still active.

让我知道这是否对您有用。