Python中的自引用类变量

时间:2017-05-27 14:56:01

标签: python django graphene-python

我正在尝试在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。将答案应用于another question

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的内容时只看到属于声明一部分的类变量。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

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

class FolderNode(DjangoObjectType):
    folders = graphene.List('FolderNode')

答案 1 :(得分:0)

一个想法:如何定义在创建类时未考虑的属性,如下所示

class FolderNode(DjangoObjectType):
    @property
    def folders(self):
        return graphene.List(FolderNode)