jeudi 29 octobre 2015

SQLAlchemy: Passing table columns into function while filtering query

I'm using a SQLite database with SQLAlchemy and attempting the following query:

affected_facilities = session.query(Facility).filter(grid.in_grid(
                                                lon_min=Facility.lon_min,
                                                lon_max=Facility.lon_max,
                                                lat_min=Facility.lat_min,
                                                lat_max=Facility.lat_max)).all()

Here, Facility is a mapped class with columns lon_min, lon_max, lat_min, and lat_max as Floats. An instance of this class can be thought of a rectangle with some extra properties.

A grid for these purposes is just another rectangle. The grid.in_grid function is determining if any vertices from a Facility's rectangle falls inside the grid's rectangle. The code is shown here:

def in_grid(self, lon_min=0, lon_max=0, lat_min=0, lat_max=0):
    # check if a vertex is within the boundaries of the grid
    if ((lon_min > self.lon_min and
            lon_min < self.lon_max and
            lat_min > self.lat_min and
            lat_min < self.lat_max) or
        (lon_min > self.lon_min and
            lon_min < self.lon_max and
            lat_max > self.lat_min and
            lat_max < self.lat_max) or
        (lon_max > self.lon_min and
            lon_max < self.lon_max and
            lat_min > self.lat_min and
            lat_min < self.lat_max) or
        (lon_max > self.lon_min and
            lon_max < self.lon_max and
            lat_max > self.lat_min and
            lat_max < self.lat_max)):
        return True
    else:
        return False

I am new to SQLAlchemy, and it is possible I have misunderstood how a filter works... If any vertex falls inside the grid, this function returns True.

When I attempt the query, I get a traceback:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "functions.py", line 25, in process_shakemaps
    lat_max=Facility.lat_max)).all()
  File "objects.py", line 311, in in_grid
    if ((lon_min > self.lon_min and
  File "/Library/Python/2.7/site-packages/sqlalchemy/sql/elements.py", line 2746, in __bool__
    raise TypeError("Boolean value of this clause is not defined")
TypeError: Boolean value of this clause is not defined

Aucun commentaire:

Enregistrer un commentaire