使用外键向后获取django对象

时间:2018-03-01 08:54:14

标签: python django

我使用Django Framework有3个模型:

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)

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

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分: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')