Alex Barry
Alex Barry

Reputation: 425

SQLAlchemy Filter Manager not returning any Values

I'm trying to create a Filter Manager to wrap up Filter Calls in a SQLAlchemy app. However, the filter manager is not returning any values. Moreover, it does not even appear to be running the SQL Statement. Is there an issue with how my session is declared?

class FilterManager():

    def __init__(self):
        self.page = 1
        self.pageLength = 5
        Logger.info('Filter: Filter Manager Created')

def SimpleFilter(self):
        limit = self.pageLength
        offset = ((self.page - 1) * self.pageLength) + 1
        session = Session()
        return session.query(KeyAction).order_by(KeyAction.id)[limit:offset]
        session.close()

Then I add a key action, which succeeds:

session = Session()
ka = KeyAction(name='Key Action 1', description = 'Test', custom = False)
session.add(ka)
session.commit()
session.close()

My unit tests all fail on the same assertion:

results = filter.SimpleFilter()
self.assertEquals(len(results), 1)

Saying that the length of results is 0, not 1.

I've also tried declaring a single session in global scope, but this had the same problem. Any help would be much appreciated!

Alex

------------------Edit------------------

Based on the first answer below, I made the following updates:

def SimpleFilter(self):
        limit = ((self.page - 1) * self.pageLength)
        offset = self.pageLength + ((self.page - 1) * self.pageLength)
        session = Session()
        results = session.query(KeyAction).order_by(KeyAction.id)[limit:offset]
        session.close()
        return results

Now it returns the result based on what was committed the previous time the script was run (0 results returned the first time, 3 returned the second time, 5 returned every time after that)

Quick Note, I did move the session declaration to right after the session factory declaration, as per the example here.

Why can't I read data written to the DB in this session?

Upvotes: 0

Views: 87

Answers (1)

Klaus D.
Klaus D.

Reputation: 14369

This might be cause by your LIMIT/OFFSET. The slice notation with [] does not allow you so define the LIMIT and OFFSET values. Instead you have to supply a Python-style range with start and end, e.g.:

[10:20]

This will return 10 items (10 to 19, zero-based).

Also, a statement after a return will never be executed.

Upvotes: 1

Related Questions