1

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)
1
  • You should be able to get it as student.address. Commented Oct 27, 2021 at 11:56

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.