0

我正在尝试简化我的 graphene-django 视图,使其具有单个石墨烯查询,该查询根据是否发送参数返回 graphene.List 或 graphene.Field。

我正在尝试以下代码,但我不确定如何处理 List 和 Field 响应之间的变化;

    """ 
        graphene.Field & graphene.List will not be determined until the resolver 'resolve_employee' 
        checks if a employeeId param is sent.

        Issue : How can I make this generic to return a list or a field
    """


    employee = graphene.Field(EmployeeType, employeeId=graphene.Int())

    def resolve_employee(self, info, **kwargs):
        employeeId = kwargs.get('employeeId')
        if employeeId is not None:
            return Employee.objects.get(pk=employeeId)
        else:
            return Employee.objects.all()

这是我当前的 schema.py,有两个单独的

class EmployeeType(DjangoObjectType):
    class Meta:
        model = Employee


class Query(object):)
    allEmployees = graphene.List(EmployeeType, active=graphene.Boolean())
    employeeDetail = graphene.Field(EmployeeType, employeeId=graphene.Int())

        
    def resolve_allEmployees(self, info, **kwargs):
        active_param = kwargs.get('active')
        if type(active_param) == bool:
            return Employee.objects.filter(term_date__isnull=active_param)
        return Employee.objects.all()


    def resolve_employeeDetail(self, info, **kwargs):
        employeeId = kwargs.get('employeeId')
        if employeeId is not None:
            return Employee.objects.get(pk=employeeId)
4

1 回答 1

2

具有打开参数的输出格式不符合 graphQL 的精神。employeeId但是,您可以通过使用作为过滤器并将输出作为列表返回来保持相同的输出格式来解决您的问题。例如:

def resolve_Employees(self, info, **kwargs):
    active_param = kwargs.get('active')
    employee_id = kwargs.get('employeeId')
    employees = Employees.objects.all()
    if type(active_param) == bool:
        employees = employees.filter(term_date__isnull=active_param)
    if employee_id:
        employees =  employees.filter(id=employee_id)  # filter list to just one employee
    return employees
于 2020-07-12T15:27:00.280 回答