使用GraphQL,Graphene和Python从查询返回任何数据

时间:2019-11-26 17:07:22

标签: graphql graphene-python graphene-django

我收到以下错误:

{
  "errors": [
    {
      "message": "Unknown argument \"project_id\" on field" +
                 \"get_project_detail_summary\" of type \"Query\".",
      "locations": [
        {
          "line": 2,
          "column": 30
        }
      ]
    }
  ]
}

使用以下查询:

query GetProjectDetailSummary($project_id: Int) {
  get_project_detail_summary(project_id: $project_id) {
    comments {
      ... on ManagerCommentNode {
        id
        text
        created
      }
      ... on VendorCommentNode {
        id
        text
        created
      }
      ... on TenantCommentNode {
        id
        text
        created
      }
    }
  }
}

使用以下后端代码,如何到达断点?或者如何给定数字的自定义数据发送回去?

class CommentsUnion(graphene.types.union.Union):
    class Meta:
        name = 'CommentsUnion'
        types = (ManagerCommentNode, VendorCommentNode, TenantCommentNode, )


class ProjectSummaryInput(graphene.InputObjectType):
    project_id = graphene.Int()


class ProjectSummaryNode(graphene.ObjectType):
    Input = ProjectSummaryInput

    project_id = graphene.Int()
    comments = graphene.List(CommentsUnion)

    @classmethod
    def resolve_comments(self, *args, **kwargs):
        import pdb;pdb.set_trace()
        return ProjectSummary.select_related('comments').objects.filter(comments__created__lt=dt)

class Query(graphene.ObjectType):
    get_project_detail_summary = Field(ProjectSummaryNode)

1 个答案:

答案 0 :(得分:0)

关于错误。

请确保在project_id的{​​{1}}中添加一个kwarg(例如,在本示例中为graphene.Field,这是“字段上的未知参数”错误的原因)。

像这样:

get_project_detail_summary

关于返回任何数据。

这是一种方法(返回class Query(graphene.ObjectType): get_project_detail_summary = Field(ProjectSummaryNode, # see below for example project_id=graphene.Int() # kwarg here ) def resolve_get_project_detail_summary(self, info, **kwargs): return ProjectSummary.objects.get(id=kwargs.get('project_id')) ),但是它通过将所有内容都放在String中来取消响应的类型:

graphene.String

在前端,我们可以使用 from django.core.serializers.json import DjangoJSONEncoder class ProjectSummaryRecentUpdatesNode(graphene.ObjectType): Input = ProjectSummaryInput recent_updates = graphene.String() def resolve_recent_updates(self, resolve, **kwargs): instance = Project.objects.get(id=resolve.variable_values.get("project_id")) things = instance.things.all() # these are all from different models, and the list is a bit longer than this. querysets = ( ("scheduled", get_scheduled(things, resolve, **kwargs)), ("completed", get_completed(things, resolve, **kwargs)), ("invoices", get_invoices(things, resolve, **kwargs)), ("expenditures", get_expenditures(things, resolve, **kwargs)), ("comments", get_comments(things, resolve, **kwargs)), ("files", get_files(things, resolve, **kwargs)), ) recent_updates = [] for update_type, qs in querysets: for item in qs: item.update( { "recent_update_type": update_type } ) recent_updates.append(item) return json.dumps(recent_updates, cls=DjangoJSONEncoder) 元素import { Query } from "react-apollo";字段...,其中包含“ any”(经json序列化)数据:

JSON.parse

旁注:

如果数据类型列表不多,则创建类似<Query query={GET_PROJECT_DETAIL_SUMMARY_RECENT_UPDATES} fetchPolicy="network-only" variables={{ project_id: this.props.projectId }} > {({ loading, error, data }: QueryResult) => { if ( data && data.get_project_detail_summary_recent_updates && data.get_project_detail_summary_recent_updates.recent_updates ) { console.log(JSON.parse(data.get_project_detail_summary_recent_updates.recent_updates)) } }} </Query> 的对象,该对象具有不同模型所需的所有字段,或者创建实际的Union,这似乎是正确的方法,这样就不会丢失类型:

Union

仍然欢迎您提出更好的建议。