石墨烯中的自定义 ConnectionField

Custom ConnectionField in graphene

我不明白如何在石墨烯的 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

但是你如何 return 额外 return 列表中的内容?

答案原来是使用石墨烯ConnectionFieldclass的一种未记载的class方法,称为resolve_connection。以下作品:

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

    field.extra = 'Whatever'
    return field

正确的做法是 解释 here

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 class[=16= 时找到了它]