使用外键向后获取django对象

问题描述 投票:0回答:2

我有3个使用Django Framework的模型:

class Student(models.Model):
    name = models.CharField()
    surname = models.CharField()
class Group(models.Model):
    groupId = models.AutoField()
    name = models.CharField()
    students = models.ForeignKey(Student)
class Faculty(models.Model):
    facultyId = models.AutoField()
    students = models.ForeignKey(Student)

我需要获得所有学生的名单,并且每个学生都要有学生的小组和教师。

python django
2个回答
2
投票

那么,首先你需要修改你的模型关系。使用您当前的模型,每个学院和小组将只有一名学生。您可以将模型修改为:

class Group(models.Model):
    groupId = models.AutoField()
    name = models.CharField()

class Faculty(models.Model):
    facultyId = models.AutoField()

class Student(models.Model):
    name = models.CharField()
    surname = models.CharField()
    group = models.ForeignKey(Group)
    faculty = models.ForeighKey(Faculty)

然后,为了得到每个学生的小组和教师,你可以使用select_related。现在您的查询将如下所示:

Students.objects.all().select_related('group', 'faculty')

0
投票
class Student(models.Model):
     name = models.CharField()
     surname = models.CharField()
class Group(models.Model):
     groupId = models.AutoField()
     name = models.CharField()
     students = models.ForeignKey(Student, related_name="group")
class Faculty(models.Model):
    facultyId = models.AutoField()
    students = models.ForeignKey(Student, "related_name"="faculty")

你可以得到这个数据Student.objects.filter(group__isnull = False,faculty__isnull = False)

它将归还拥有教师和团队的学生。

对于Json数据:

class Student(serializer.ModelSerializer):
    class Meta:
       model = Student
       fields = ('name', 'surname' , 'group', 'faculty')
© www.soinside.com 2019 - 2024. All rights reserved.