查询
假设你有
- 定义如下的查询
employees = graphene.List(EmployeeType)
- 查询的解析器,例如
def resolve_employees(self, info, **kwargs):
return Employee.objects.all()
和
- 您的 Employee 模型的权限称为
can_view_salary
和can_edit_salary
然后你需要定义EmployeeType
一个salary
取决于用户的值。就像是
from graphene_django.types import DjangoObjectType
from myapp.models import Employee
class EmployeeType(DjangoObjectType):
class Meta:
model = Employee
def resolve_salary(self, info):
if info.context.user.has_perm('myapp.can_view_salary'):
return self.salary
return None
重要的一点是,您正在resolve
为根据权限值切换的薪水创建自定义函数。您不需要为first_name
和创建任何其他解析器last_name
。
突变
首先阅读文档。 但是没有进行更新的示例。
简而言之,您可以采用以下方法:
- 创建一个方法以在您的
Mutation
方法中设置员工
class MyMutations(graphene.ObjectType):
set_employee = SetEmployee.Field()
- 创建一个
SetEmployee
获取 Employee 对象并更新它的方法。对于某些用户,薪水字段会被忽略。
class SetEmployee(graphene.Mutation):
class Arguments:
id = graphene.ID()
first_name = graphene.String()
last_name = graphene.String()
salary = graphene.String()
employee = graphene.Field(lambda: EmployeeType)
@classmethod
def mutate(cls, root, info, **args):
employee_id = args.get('employee_id')
# Fetch the employee object by id
employee = Employee.objects.get(id=employee_id)
first_name = args.get('first_name')
last_name = args.get('last_name')
salary = args.get('salary')
# Update the employee fields from the mutation inputs
if first_name:
employee.first_name = first_name
if last_name:
employee.last_name = last_name
if salary and info.context.user.has_perm('myapp.can_edit_salary'):
employee.salary = salary
employee.save()
return SetEmployee(employee=employee)
注意:最初编写此答案时,Graphene Django 中没有可用的 Decimal 字段——我通过将字符串作为输入来避免这个问题。