如何在graphene-python DjangoObjectType

时间:2019-04-05 06:26:52

标签: python django graphene-python

我有一个 graphene-python DjangoObjectType 类,我想添加一个自定义类型,但是我不知道如何在resolver函数中获取当前模型实例。我正在关注this tutorial,但找不到任何参考。

这是我的 DjangoObjectTypeClass

class ReservationComponentType(DjangoObjectType):
    component_str = graphene.String()

    class Meta:
        model = ReservationComponent

    def resolve_component_str(self, info):
        # How can I get the current ReservationComponent instance here?. I guess it is somewehere in 'info', 
        # but documentation says nothing about it

        current_reservation_component = info.get('reservation_component')
        component = current_reservation_component.get_component()

        return component.name

我的问题与Graphene resolver for an object that has no model不同,因为我的对象具有模型。我不知道为什么将其标记为“可能重复”并具有如此明显的区别。我的问题确实是基于模型的。

1 个答案:

答案 0 :(得分:0)

是的,它位于info中的某个位置,即这里:

type_model = info.parent_type.graphene_type._meta.model

但是,如果您使用DjangoObjectType,则实例将传递到self。因此,您可以采用另一种方式:

class ReservationComponentType(DjangoObjectType):
    component_str = graphene.String()

    class Meta:
        model = ReservationComponent

    def resolve_component_str(self, info):
        # self is already an instance of type's model (not sure if it is in all cases):
        component_class = self.__class__

        current_reservation_component = info.get('reservation_component')
        component = current_reservation_component.get_component()

        return component.name