我试图将单个对象查询限制为创建它们的用户。
Models.py
class Env(models.Model):
name = models.CharField(max_length=50)
user = models.ForeignKey(
User, on_delete=models.CASCADE)
description = TextField()
Schema.py
class EnvNode(DjangoObjectType):
class Meta:
model = Env
filter_fields = {
'name': ['iexact'],
'description': ['exact', 'icontains'],
}
interfaces = (relay.Node, )
Query(object):
env = relay.Node.Field(EnvNode)
all_envs = DjangoFilterConnectionField(EnvNode)
我尝试添加解析查询,但是它与过滤器only worked for the "all_env" query配合使用,不适用于单个对象查询
def resolve_env(self, info):
env = Env.objects.filter(user = info.context.user.id)
if env is not None:
return env
else:
return None
还尝试按照推荐的here under filtering Node based ID access向EnvNode添加类方法:
@classmethod
def get_node(context, cls, id, info):
try:
env = cls._meta.model.objects.get(id = id)
except cls._meta.model.DoesNotExist:
return None
if context.user == env.user:
return env
return None
但我遇到了错误:
"message": "get_node() missing 1 required positional argument: 'info'",
答案 0 :(得分:1)
似乎文档不正确,而且您的参数对于 get_node 方法的顺序也不正确。
该通话只有三个参数
您应该这样写才能使限制生效:
@classmethod
def get_node(cls, info, id):
try:
env = cls._meta.model.objects.get(id=id, user=info.context.user)
except cls._meta.model.DoesNotExist:
return None
return env
希望有帮助。