Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
How to query from multiple models in django

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)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!