Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda