1

我正在尝试在 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 时只看到作为声明一部分的类变量。有任何想法吗?

4

2 回答 2

2

基于https://github.com/graphql-python/graphene/issues/110,正确的方法是使用字符串:

class FolderNode(DjangoObjectType):
    folders = graphene.List('FolderNode')
于 2017-05-27T15:07:39.253 回答
0

一个想法:定义一个在类创建时不考虑的属性怎么样,如下

class FolderNode(DjangoObjectType):
    @property
    def folders(self):
        return graphene.List(FolderNode)
于 2017-05-27T15:00:36.577 回答