Home > Net >  How to query from multiple models in django
How to query from multiple models in django

Time:10-28

I am trying to understand the most efficient way to query the data needed from multiple tables in Django.

class City():
    name = models.CharlField()

class Address():
    line1 = models.CharlField()
    ...
    city_id = models.ForeignKey(City, ... related_name="city_address")

class Student()
   name = models.CharlField()
   gender = models.CharlField()
   # a student can only have one address
   address_id = models.OneToOneField(Address, ... related_name="address_student")

How can I optimize the query below to get the city this student belongs to?

student = Student.objects.filter(name="John").first() # assuming its a unique name
address_id = student.address_id
address = Address.objects.filter(id=address).first()
city_id = address.city_id

City.objects.get(id=city_id)

Thank you in advance.

CodePudding user response:

You can query with:

City.objects.get(address__student=mystudent)

This will produce a query that looks like:

SELECT city.*
FROM city
INNER JOIN address ON address.city_id_id = city.id
INNER JOIN student ON student.address_id_id = address.id
WHERE student.id = id_of_the_student
  • Related