lakshmen
lakshmen

Reputation: 29064

Making queries that involves ForeignKey in Django

Apologies on the last question. Should have phrased it better.

I have three classes, Student and another Adult and AdultProfile. I would like to make a query such that it gets all the adults who are from US but it has to be done using Student class. This is because my queryset is Student.objects.all() and based on this queryset, i would like to get all the adults(through AdultProfile) from US . This is an example of the code while the original code much more complex and longer. This example shows the gist of the problem.

class Student(models.Model):
   name = models.CharField(max_length=255)
   birthday= models.DateField(blank=True,null=True)

class Adult(models.Model):
   user = models.OneToOneField(User)
   parent= models.ForeignKey(Student,related_name="relationships")

class AdultProfile(models.Model):
   country = models.CharField(max_length=2)
   adult = models.OneToOneField(Adult,related_name='profile')

Need some help in this.. Hope i have phrased it better this time...

Upvotes: 0

Views: 254

Answers (1)

You're not going to be able to do this from a Student queryset. The only way you will end up with Adult objects from a Student class is from a Student instance via its reverse-related-accessor: student_instance.relationships.all().

The missing ingredient in your django ORM travels is probably the fact that you can query related objects (FK, OneToOne) via its related_name (or by default, the model name).

student_qs = Student.objects.all() # some query
adults_in_us = Adult.objects.filter(parent__in=student_qs, profile__country='US')

Upvotes: 1

Related Questions