1

我不明白如何在石墨烯的 ConnectionField 中使用自定义字段。我有类似的东西:

class ShipConnection(Connection):
    extra = String()

    class Meta:
        node = Ship

SHIPS = ['Tug boat', 'Row boat', 'Canoe']

class Query(AbstractType):
    ships = relay.ConnectionField(ShipConnection)

    def resolve_ships(self, args, context, info):
        return ShipConnection(
            extra='Some extra text',
            edges=???
        )

通常,你会说:

    def resolve_ships(self, args, context, info):
        return SHIPS

但是你如何额外返回一些东西返回一个列表?

4

2 回答 2

1

答案是使用石墨烯类的未记录类方法ConnectionField,称为resolve_connection. 以下作品:

def resolve_ships(self, args, context, info):
    field = relay.ConnectionField.resolve_connection(
        ShipConnection,
        args,
        SHIPS
    )

    field.extra = 'Whatever'
    return field
于 2017-09-13T13:41:53.530 回答
1

执行此操作的正确方法在此处进行了准确解释。

class Ship(graphene.ObjectType):
    ship_type = String()

    def resolve_ship_type(self, info):
         return self.ship_type

    class Meta:
          interfaces = (Node,)

class ShipConnection(Connection):
    total_count = Int() # i've found count on connections very useful! 

    def resolve_total_count(self, info):
        return get_count_of_all_ships()

    class Meta:
        node = Ship

    class Edge:
        other = String()
        def resolve_other(self, info):
            return "This is other: " + self.node.other

class Query(graphene.ObjectType):
    ships = relay.ConnectionField(ShipConnection)

    def resolve_ships(self, info):
        return get_ships_from_database_or_something_idk_its_your_implmentation()

schema = graphene.Schema(query=Query)

我不知道这是否被推荐,但该resolve_total_count方法也可以实现为:

def resolve_total_count(self, info):
    return len(self.iterable)

我不知道该属性是否记录在任何地方,但我在调查课程iterable时能够找到它Connection

于 2021-08-06T16:29:31.390 回答