从外键相关模型的属性检索到另一个外键相关字段模型的属性

时间:2019-06-25 10:05:16

标签: python django django-rest-framework

因此,我有三个模型,它们以不同的关系彼此关联。首先,父模型与使用外键关系的学生相关,学生模型也与使用外键关系的出勤模型相关。我想创建一个序列化程序,在这里我可以分别检索每个父母的孩子的出勤率。如何才能做到这一点?

models.py


class Parent(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None)
    child = models.ForeignKey(Student, on_delete=models.CASCADE)
    email = models.EmailField(null=True)

    def __str__(self):
        return self.user.firstName + ' ' + self.user.lastName

class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None)
    batch = models.ForeignKey(Batch, on_delete=models.CASCADE, null=True, related_name='students')
    age = models.IntegerField(blank=True)

    @property
    def remarks(self):
        return self.remark_set.all()

    @property
    def marks(self):
        return self.marks_set.all()

    def __str__(self):
        return self.user.firstName + ' ' + self.user.lastName

class Attendance(models.Model):
    Subject = models.ForeignKey(Subject, on_delete=models.CASCADE, null=True)
    class_date = models.DateField(blank=True, null=True)
    student = models.ForeignKey(Student, related_name='student_today', on_delete=models.CASCADE, null=True)
    present = models.NullBooleanField(default=False)

    def __str__(self):
        return str(self.class_date) + '_' + str(self.student.user.username) + '_' + str(self.Subject.name)

serilaizers.py

class BasicUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('firstName', 'lastName')


class BasicStudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ('batch', 'age')


class ParentSerializer(serializers.ModelSerializer):
    user = BasicUserSerializer(read_only=True, many=False)
    child = BasicStudentSerializer(read_only=True,  many= False)

    class Meta:
        model = Parent
        fields = "__all__"

views.py

class ParentView( mixins.ListModelMixin, mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    queryset = Parent.objects.all()
    serializer_class = serializers.ParentSerializer

0 个答案:

没有答案