Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python GraphQL How to declare a self-referencing graphene object type

I have a django model which has a foreign key related to itself, I want to represent this model as a graphene ObjectType.

I know it is trivial to do this using DjangoObjectType from the graphene_django library.

I am looking for an elegant python solution without using graphene_django.

An example of a model I want to represent

# models.py
class Category(models.Model):
    name = models.CharField(unique=True, max_length=200)
    parent = models.ForeignKey(
        'self', on_delete=models.SET_NULL, null=True, blank=True,
        related_name='child_category')

the schema below obviously does not scale and the ParentCategoryType does not have the parent field so it is not strictly a parent of CategoryType.

# schema.py
class ParentCategoryType(graphene.ObjectType):
    id = graphene.types.uuid.UUID()
    name = graphene.String()

class CategoryType(graphene.ObjectType):
    id = graphene.types.uuid.UUID()
    name = graphene.String()
    parent = graphene.Field(ParentCategoryType)

the code below gives a CategoryType undefined error.

#schema.py
class CategoryType(graphene.ObjectType):
    id = graphene.types.uuid.UUID()
    name = graphene.String()
    parent = graphene.Field(CategoryType)

Any help much appreciated.

like image 898
dcreekp Avatar asked Oct 30 '19 11:10

dcreekp


1 Answers

After doing some research, I came across a GitHub issue that tracks this. The answer seems to be here. I tried this myself and it works. So in your case, you would just change the code to read parent = graphene.Field(lambda: ParentCategoryType) and parent = graphene.Field(lambda: CategoryType)

like image 96
mattbeiswenger Avatar answered Nov 12 '22 02:11

mattbeiswenger