我有一个带有计算属性字段的简单 django 模型clicks
。该模型如下所示:
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 端点中可以访问。所以我创建了以下类型和查询:
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 资源管理器中使用以下查询:
{
link(id: 3) {
id,
url,
clicks{
clicks,
dt
}
}
}
我的预期结果是这样的:
{
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?
编辑:
我使用了@mark-chackerian 答案的修改版本来解决问题:似乎我对石墨烯的“魔力”期待太多,我必须明确告诉它每个字段是如何解决的。
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']