我有一个带有计算属性字段clicks
的简单django模型。该模型如下所示:
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 explorer中使用以下查询:
{
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}
]
}
那我在这里做错了什么?如何在石墨烯中将dicts列表转换为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']
答案 0 :(得分:1)
您必须更明确地告诉石墨烯如何制作Stats
对象列表。
尝试这样的事情:
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]