结合DjangoObjectType和ObjectType [英] Combine DjangoObjectType and ObjectType

查看:60
本文介绍了结合DjangoObjectType和ObjectType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的django模型,其计算所得的属性字段为 clicks .该模型如下所示:

I have a simple django model with a calculated property field clicks. The model looks like this:

class Link(models.Model):
    url = models.URLField()

    @property
    def clicks(self):
        """
        Property does some calculations and returns a list of dictionaries:

        """
        # removed calculation for simplicity
        return [{'dt': 1, 'clicks': 100}, {'dt': 2, 'clicks': 201}] 

我想在我的graphql端点中使该模型可访问.因此,我创建了以下类型和查询:

I want to make this model accesible in my graphql endpoint. So I created the following Types and Query:

class Stats(graphene.ObjectType):
    clicks = graphene.String()
    dt = graphene.String()


class LinkType(DjangoObjectType):
    clicks = graphene.List(Stats, source='clicks')

    class Meta:
        model = Link


class Query(object):
    link = graphene.Field(LinkType, id=graphene.Int())

    def resolve_link(self, info, **kwargs):
        id = kwargs.get('id')
        url = kwargs.get('url')
        if id is not None:
            return Link.objects.get(pk=id)
        return None

现在,我应该能够在我的graphql资源管理器中使用以下查询:

Now I should be able to use the following query in my graphql explorer:

{
  link(id: 3) {
    id,
    url,
    clicks{
      clicks,
      dt
    }
  }
}

我的预期结果将是这样:

My expected result would be like this:

{
  id: 3,
  url: "www.google.de",
  clicks: [
    dt: 1, clicks: 100},
    dt: 2, clicks: 201}
  ]
}

但是 clicks dt 的嵌套值为 null :

{
  id: 3,
  url: "www.google.de",
  clicks: [
    dt: null, clicks: null},
    dt: null, clicks: null}
  ]
}

那么我在这里做错了什么?如何将字典列表转换为石墨烯中的ObjectType?

So what am I doing wrong here? How can I convert a list of dicts to an ObjectType in graphene?

我使用了@ mark-chackerian答案的修改版本来解决此问题:似乎我对石墨烯的期望太高了,我必须明确地告诉它如何解决每个字段.

I used a modified version of @mark-chackerian answer to solve the problem: Seems like I was expecting too much "magic" from graphene and I have to explicitly tell it how every field is resolved.

class Stats(graphene.ObjectType):
    clicks = graphene.String()
    dt = graphene.String()

    def resolve_clicks(self, info):
        return self['clicks']

    def resolve_dt(self, info):
        return self['dt']

推荐答案

您必须更明确地告诉石墨烯如何制作 Stats 对象的列表.

You have to tell graphene more explicitly how to make your list of Stats objects.

尝试这样的事情:

class LinkType(DjangoObjectType):
    clicks = graphene.List(Stats)

    class Meta:
        model = Link

    def resolve_clicks(self, info):
        return [Stats(dt=click_dict['dt'], clicks=click_dict['clicks') for click_dict in self.clicks]

这篇关于结合DjangoObjectType和ObjectType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆