Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the number of rows in table using SQLAlchemy

I am using SQLAlchemy in Python, and I want to know how to get the total number of rows in a column. I have variables defined:

engine = sqlalchemy.create_engine(url, ehco=False) Session = sqlalchemy.orm.sessionmaker(bind=engine) Session = session() metadata = sqlalchemy.MetaData(engine) Base = declarative_base(metadata=metadata)  # A class representing the shape_congress_districts_2012 table class Congress(Base):     __tablename__ = 'shape_congress_districts_2012'     id = geoalchemy.Column(sqlalchemy.Integer, primary_key=True)     name = geoalchemy.Column(sqlalchemy.Unicode)     geom = geoalchemy.GeometryColumn(geoalchemy.Polygon(2))     geom_simple = geoalchemy.GeometryColumn(geoalchemy.Polygon(2))     area = geoalchemy.Column(sqlalchemy.Float)     state_id = geoalchemy.Column(sqlalchemy.Integer)     census_year = geoalchemy.Column(sqlalchemy.Date)  geoalchemy.GeometryDDL(Congress.__table__) 

I want to determine the total number of rows in the table without having to wait a whole bunch of time querying the database. Currently, I have a bit of code:

rows = session.query(Congress).all() 

Then I can access them from list, but this requires me to load everything into memory at once.

like image 238
dbmikus Avatar asked May 30 '12 19:05

dbmikus


People also ask

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.

What is all () in SQLAlchemy?

method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.


1 Answers

This should work

rows = session.query(Congress).count() 

EDIT: Another way related to my first try

from sqlalchemy import func rows = session.query(func.count(Congress.id)).scalar() 
like image 132
Diego Navarro Avatar answered Sep 28 '22 20:09

Diego Navarro