石墨烯-Django和多对多关系查找

时间:2019-10-11 14:18:49

标签: django graphql graphene-python graphene-django django-graphql-jwt

我有两个Django模型-Teacher和Student,并且具有多对多关系。老师可以有多个学生,而学生可以有多个老师。有一种称为“备注”的“通过”模式,教师可以将学生标记为“最喜欢的”。

我是GraphQL的新手。我正在尝试实现两个查询:
1.老师和所有学生
2.老师和他们喜欢的学生

我在执行第二个查询时遇到困难,并且无法执行。

models.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")
    ))

schema.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]

0 个答案:

没有答案