【问题标题】:Custom ConnectionField in graphene石墨烯中的自定义 ConnectionField
【发布时间】:2018-02-21 02:29:19
【问题描述】:

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

但是你如何返回额外的东西并且返回一个列表呢?

【问题讨论】:

    标签: relay graphene-python


    【解决方案1】:

    正确的方法是完全解释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 类时能够找到它

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-13
        • 2017-05-11
        • 2022-01-24
        • 2019-12-20
        • 2018-01-11
        • 2020-09-01
        • 2019-06-13
        • 2020-01-08
        相关资源
        最近更新 更多