How can I resolve custom fields for django models using django_graphene?
Asked Answered
A

1

5

Looking at graphene_django, I see they have a bunch of resolvers picking up django model fields mapping them to graphene types.

I have a subclass of JSONField I'd also like to be picked up.

:

# models
class Recipe(models.Model):
    name = models.CharField(max_length=100)
    instructions = models.TextField()
    ingredients = models.ManyToManyField(
        Ingredient, related_name='recipes'
    )
    custom_field = JSONFieldSubclass(....)


# schema
class RecipeType(DjangoObjectType):
    class Meta:
        model = Recipe

    custom_field = ???

I know I could write a separate field and resolver pair for a Query, but I'd prefer it to be available as part of the schema for that model.

What I realize I could do:

class RecipeQuery:
    custom_field = graphene.JSONString(id=graphene.ID(required=True))

    def resolve_custom_field(self, info, **kwargs):
       id = kwargs.get('id')
       instance = get_item_by_id(id)
       return instance.custom_field.to_json()

But -- this means a separate round trip, to get the id then get the custom_field for that item, right?

Is there a way I could have it seen as part of the RecipeType schema?

Anagrammatize answered 11/10, 2018 at 19:14 Comment(0)
A
6

Ok, I can get it working by using:

# schema
class RecipeType(DjangoObjectType):
    class Meta:
        model = Recipe

    custom_field = graphene.JSONString(resolver=lambda my_obj, resolve_obj: my_obj.custom_field.to_json())

(the custom_field has a to_json method)

I figured it out without deeply figuring out what is happening in this map between graphene types and the django model field types.

It's based on this: https://docs.graphene-python.org/en/latest/types/objecttypes/#resolvers

Same function name, but parameterized differently.

Anagrammatize answered 11/10, 2018 at 21:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.