【问题标题】:Graphene Python Lists resolve null for all fields石墨烯 Python 列表为所有字段解析 null
【发布时间】:2018-04-07 00:24:58
【问题描述】:

我在 python 中使用 GraphQL 正在尝试解析列表数据,但字段解析为 null。我怎样才能让他们返回实际的列表数据?

这是我的代码的 sn-p

import graphene


class User(graphene.ObjectType):
    """ Type definition for User """
    id = graphene.Int()
    username = graphene.String()
    email = graphene.String()

class Query(graphene.ObjectType):
    users = graphene.List(User)

    def resolve_users(self, args):
        resp = [{'id': 39330, 'username': 'RCraig', 'email': 
                 'WRussell@dolor.gov', 'teamId': 0}, {'id': 39331, 
                 'username': 'AHohmann','email': 'AMarina@sapien.com', 
                 'teamId': 0}]
        return  resp

schema = graphene.Schema(query=Query)

可以在graphene playground测试sn-p

这是我当前的查询

以及不受欢迎的响应

【问题讨论】:

    标签: python graphql graphene-python


    【解决方案1】:

    您需要返回用户的对象,而不仅仅是字典:

    import graphene
    
    
    class User(graphene.ObjectType):
        """ Type definition for User """
        id = graphene.Int()
        username = graphene.String()
        email = graphene.String()
    
    class Query(graphene.ObjectType):
        users = graphene.List(User)
    
        def resolve_users(self, args):
            resp = [User(id=39330, username='RCraig', email='WRussell@dolor.gov')]
            return  resp
    
    schema = graphene.Schema(query=Query)
    

    您可以签入playground

    【讨论】:

    • 此代码仅返回一个列表(一组 id、用户名、电子邮件)。如何退回多套?
    • @jigarshah 我知道这已经晚了,但您只需在上面的代码中向resp 添加更多User 对象。
    猜你喜欢
    • 2021-06-28
    • 2021-03-14
    • 2020-08-18
    • 2022-10-25
    • 2020-06-24
    • 2019-04-03
    • 2017-11-02
    • 2019-11-18
    • 1970-01-01
    相关资源
    最近更新 更多