我正在做关于过滤的石墨烯教程:http://docs.graphene-python.org/projects/django/en/latest/filtering/ 用户被限制查询先前创建的对象的位置。我正在使用石墨烯2,django 2和django-filter 1.11。
class AnimalFilter(django_filters.FilterSet):
# Do case-insensitive lookups on 'name'
name = django_filters.CharFilter(lookup_expr=['iexact']) #changed this to work
class Meta:
model = Animal
fields = ['name', 'genus', 'is_domesticated']
@property
def qs(self):
# The query context can be found in self.request.
return super(AnimalFilter, self).qs.filter(owner=self.request.user)
我正在插入self.request.user
部分,其中加载了用户数据。当我进行如下查询时:
query {
allAnimalss {
edges {
node {
id,
name
}
}
}
}
我在查询字段中收到错误:
{
"errors": [
{
"message": "'NoneType' object has no attribute 'user'",
"locations": [
{
"line": 2,
"column": 3
}
]
}
],
"data": {
"allAnimals": null
}
}
如果我删除过滤器,它可以正常工作。该教程提到"由经过身份验证的用户拥有(在context.user中设置)。"这是什么意思?
我尝试将get_context_data函数添加到views.py
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['user'] = self.request.user
return context
并将self.request.user
更改为self.context.user
但不起作用
答案 0 :(得分:1)
您可以通过resolver方法中的info.context访问请求,从而访问用户。文档不能很好地解释这一点,但是here you can see an example
def resolve_something(self, info, something_id):
# Here info.context is the django request object
something = Something.objects.get(something_id)
if info.context.user.id == something.user_id:
# The user owns this object!
return something
# Return None or raise an exception here maybe since it's not the owner
return None