我有两个 Django 模型——教师和学生,并且有一个多对多的关系。教师可以有多个学生,学生可以有多个教师。有一种称为“备注”的“通过”模型,教师可以将学生标记为最喜欢的。
我是 GraphQL 的新手。我正在尝试实现两个查询:
1. 老师和他们所有的学生
2. 老师和他们最喜欢的学生
我在实施第二个查询时遇到了困难,并且一直无法这样做。
模型.py
SUBJECTS = (
("Maths", "Maths"),
("Chemistry", "Chemistry"),
("Physics", "Physics")
)
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField(default=0)
def __str__(self):
return self.name
class Teacher(models.Model):
name = models.CharField(max_length=100)
subject = models.CharField(max_length=100, choices=SUBJECTS)
students = models.ManyToManyField(Student, through="Remarks")
def __str__(self):
return self.name
class Remarks(models.Model):
student = models.ForeignKey(Student, related_name="student", on_delete=models.DO_NOTHING)
teacher = models.ForeignKey(Teacher, related_name="teacher", on_delete=models.DO_NOTHING)
favorite = models.BooleanField(default=False, choices=(
(True, "Yes"),
(False, "No")
))
架构.py
import graphene
from graphene import relay, ObjectType
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from .models import Teacher, Student, Remarks
class RemarkNode(DjangoObjectType):
class Meta:
model = Remarks
filter_fields = ['favorite']
interfaces = (relay.Node, )
class TeacherNode(DjangoObjectType):
favorite = graphene.Field(RemarkNode)
class Meta:
model = Teacher
filter_fields = ['name', 'subject']
interfaces = (relay.Node, )
class StudentNode(DjangoObjectType):
class Meta:
model = Student
filter_fields = {
'name': ['exact', 'icontains', 'istartswith'],
'age': ['exact'],
'favorite': ['exact']
}
interfaces = (relay.Node, )
class Query(graphene.ObjectType):
teacher = relay.Node.Field(TeacherNode)
all_teachers = DjangoFilterConnectionField(TeacherNode)
student = relay.Node.Field(StudentNode)
all_students = DjangoFilterConnectionField(StudentNode)
def resolve_favorites(self, info, **kwargs):
teacher = Teacher.objects.get(pk=self.id)
remarks = Remarks.objects.filter(teacher=teacher)
return [each.student for each in remarks]