如何在石墨烯中获取模型的当前实例-python DjangoObjectType

How to get current instance of model in graphene-python DjangoObjectType

我有一个graphene-python DjangoObjectType class,我想添加一个自定义类型,但我不知道如何获取解析器函数中的当前模型实例。我正在关注 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 不同,因为我的对象确实有模型。我不知道为什么它被标记为 "possible duplicated" 有如此明显的差异。我的问题确实是基于模型。

是的,它在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