Search code examples
pythondjangographene-python

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


I have a graphene-python DjangoObjectType class, and I want to add a custom type, but I don't know how to get the current model instance in the resolver function. I am following this tutorial, but I can't find any reference.

This is my 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

My question is different from Graphene resolver for an object that has no model, because my object DOES HAVE A MODEL. I don't know why it was marked as "possible duplicated" with such an evident difference. My question is, indeed, based on the model.


Solution

  • Yes, it is somewhere in info, namely here:

    type_model = info.parent_type.graphene_type._meta.model
    

    But if you use DjangoObjectType, then instance is passed to self. So you may go another way:

    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