【问题标题】:How to get current instance of model in graphene-python DjangoObjectType如何在graphene-python DjangoObjectType中获取模型的当前实例
【发布时间】:2019-08-27 00:05:58
【问题描述】:

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

【问题讨论】:

  • @PetarP 不,这不是一个重复的问题,因为我的对象确实有一个模型,而且我的问题确实基于这样的模型。您引用的问题与我要解决的问题有关
  • 操作,抱歉,没有正确阅读,将删除它。
  • 嘿,这里,docs中有很好的例子

标签: python django graphene-python


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 2013-02-03
    • 2015-03-13
    • 2014-10-24
    • 2018-07-03
    • 2012-11-24
    • 2017-01-23
    • 2019-11-15
    • 2020-05-19
    相关资源
    最近更新 更多