我正在尝试在 Graphene-Django 中实现类似文件夹的类型。文件夹可以包含文件或文件夹。这样做:
Django模型:
from django.db import models
class Folder(models.Model):
name = models.CharField(...)
parent = models.ForeignKey('self')
class File(models.Model):
name = models.CharField(...)
content = models.TextField(...)
石墨烯API:
from files.models import Folder, File
class FolderNode(DjangoObjectType):
folders = graphene.List(FolderNode)
def resolve_folders(self, args, context, info):
return Folder.objects.filter(parent=self)
class Meta:
model = Folder
失败,因为我不能FolderNode
在它自己的类定义中引用。将答案应用于另一个问题:
class FolderNode(DjangoObjectType):
def __new__(cls, *args, **kwargs):
cls.folders = graphene.List(cls)
return object.__new__(cls, *args, **kwargs)
def resolve_folders(self, args, context, info):
return Folder.objects.filter(parent=self)
class Meta:
model = Folder
也不起作用,因为 Graphene 在决定添加什么到 API 时只看到作为声明一部分的类变量。有任何想法吗?