I would like to retrieve all results of a query. My code looks like:
engine = sqlalchemy.create_engine(...)
Base = declarative_base()
class Something(Base):
...
Session = sessionmaker(bind=engine)
session = Session()
query = session.query(Something).filter(...).all()
I see query.count() == 3000
, but when I try results = query.all()
, I get a single row only (i.e. len(results) == 1
).
My understanding is that query.all()
executes the query and returns a list of all results. Am I missing something here? What are some possible reasons the counted number of rows would be greater than the number of rows returned?
Edit (some more details):
Taking the raw SQL (e.g. looking at str(query)
and making parameter substitutions) and passing it into session.execute
seems to work just fine:
# this gives 3000 rows
for row in session.execute(raw_sql, {'param1': val1, 'param2': val2}):
print(row)
Solution
Turns out the problem was that my primary key was not unique. Lesson learned: be very careful when setting up your class! In my case, I had:
class Something(Base):
row_id_1 = Column(Integer, primary_key=True)
row_id_2 = Column(Integer) # PROBLEM! Need to specify primary_key=True
value = Column(Float)
This caused problems because the primary key was the combination (row_id_1, row_id_2).
execute()
?