gpt4 book ai didi

python - Python 中的自引用类变量

转载 作者:行者123 更新时间:2023-12-01 02:56:02 26 4
gpt4 key购买 nike

我正在尝试在 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(...)

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

最佳答案

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

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

关于python - Python 中的自引用类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44218302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com