GraphQL:如何排序节点的“外键”设置项?

时间:2018-04-16 15:44:43

标签: python django graphql graphene-python

我使用Django,graphene-djangodjango-filter来构建GraphQL api并遇到orderBy的问题:

GraphiQL

一般来说:我有院系,每个院系都有几个部门。我可以对院系进行排序,但不能对各部门做同样的事情。

Django模特:

class Faculty(models.Model):
    code = models.CharField(...)

class Department(models.Model):
    code = models.CharField(...)
    faculty = models.ForeignKey(
        Faculty,
        on_delete=models.CASCADE,
        related_name="departments",
    )

为了能够对我添加的院系进行分类:

import graphene
import django_filters
from graphene import relay, ObjectType
from django_filters import OrderingFilter
from graphene_django.types import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField

class FacultyFilter(django_filters.FilterSet):
    class Meta:
        model = Faculty
        fields = ['university']
    order_by = OrderingFilter(fields=('code',))

class DepartmentFilter(django_filters.FilterSet):
    class Meta:
        model = Department
        fields = ['university', 'faculty']
    order_by = OrderingFilter(fields=('code',))

class Query(object):
    faculty = relay.Node.Field(FacultyNode)
    all_faculties = DjangoFilterConnectionField(
        FacultyNode,
        filterset_class=FacultyFilter,
    )

    department = relay.Node.Field(DepartmentNode)
    all_departments = DjangoFilterConnectionField(
        DepartmentNode,
        filterset_class=DepartmentFilter,
    )

为什么我不能对一组部门进行排序?

1 个答案:

答案 0 :(得分:0)

将此字段添加到节点:

class FacultyNode(DjangoObjectType):
    departments = DjangoFilterConnectionField(
        DepartmentNode,  # lambda: DepartmentNode (if Node is defined later)
        filterset_class=DepartmentFilter,
    )