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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With