Anna Diaconu
Anna Diaconu

Reputation: 5

Get the django object backward using foreign key

I have 3 models using 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)

I need to get the list of all students and for each one to have the student's group and faculty.

Upvotes: 0

Views: 123

Answers (2)

aman kumar
aman kumar

Reputation: 3156

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

you can get this data Student.objects.filter(group__isnull=False, faculty__isnull=False )

It will return the student who have faculty and group.

for Json data:

class Student(serializer.ModelSerializer):
    class Meta:
       model = Student
       fields = ('name', 'surname' , 'group', 'faculty')

Upvotes: 0

Martin Mogusu
Martin Mogusu

Reputation: 765

Well, first you need to modify your model relationships. With your current models, each Faculty and Group will have a single student. You can modify the model to this:

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)

Then to get the Group and faculty of each student you can use select_related. Now your query will look like this:

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

Upvotes: 2

Related Questions