Search code examples
pythondjangographqlgraphene-python

GraphQL: how to sort node's "foreign key" set items?


I use Django, graphene-django and django-filter to build GraphQL api and have a problem with orderBy:

GraphiQL

In general: I have faculties, each one has several departments. I can sort faculties but can't do the same with departments.

Django models:

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",
    )

To be able to sort faculties I added:

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,
    )

Why can't I sort a set of departments?


Solution

  • Add this field to Node:

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