我有一个 Django 模型,它具有与自身相关的外键,我想将此模型表示为 graphene 的 ObjectType
。
我知道使用 graphene_django 库中的 DjangoObjectType
很容易做到这一点。
我正在寻找一种优雅的 Python 解决方案,而不使用 graphene_django。
我想要表示的模型示例:
# 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')
下面的模式显然不具有可扩展性,
ParentCategoryType
没有parent
字段,因此严格来说不是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)
下面的代码出现了“CategoryType未定义”的错误。
#schema.py
class CategoryType(graphene.ObjectType):
id = graphene.types.uuid.UUID()
name = graphene.String()
parent = graphene.Field(CategoryType)
非常感谢您的帮助。