django休息相关记录序列化

时间:2014-08-15 11:53:44

标签: django django-rest-framework

我目前正在开发一个使用django休息的学校系统。我有一个表格,主题,学生和表主题出勤连接科目和学生。还有表等级,收集所有等级,并与主题出勤相关联。

我想提出这样的API请求: API /科目?学生= 1 查看该学生的所有科目。使用过滤很容易。但是如何只显示该学生的成绩而不是所有给定的学科成绩?序列化关系将给我所有成绩......

我有这个型号:

class Subject(models.Model):
    teachers = models.ManyToManyField(Teacher, through='SubjectManagement', related_name='subjects')
    students = models.ManyToManyField(Student, through='SubjectAttendance', related_name='subjects')
    ...
    def getStudentGrades(self,id):
        now = datetime.datetime.now
        gs = Grade.objects.filter(subjectAttendance__student__id = id, subjectAttendance__start__lte=now,
                             subjectAttendance__end__gte=now)
        return json.dumps(gs)


class SubjectAttendance(models.Model):
    student = models.ForeignKey(Student)
    subject = models.ForeignKey(Subject)
    start = models.DateTimeField()
    end = models.DateTimeField()

class Grade(models.Model):
    subjectAttendance = models.ForeignKey(SubjectAttendance)
    ...

    def __unicode__(self):
        return json.dumps(self)

我现在也有简单的序列化器:

class SubjectSerializer(serializers.ModelSerializer):
    grades = serializers.Field(source='getStudentGrades')

    class Meta:
        model = Subject

的问候,

0 个答案:

没有答案