Python SQLAlchemy dynamically build select statements
I am currently trying to write a function that takes arguments, if the arguments are not false then it builds the select statement with them in it. I am unable to get it to work unless I am too build the select statement as an object all in one line. Separating the select statement causes it to ignore and not even include it. Is there way to build select statements dynamically?
def search_land(
session: Session,
longitude: float | bool = False,
latitude: float | bool = False,
entity: str | bool = False,
address: str | bool = False,
county: str | bool = False,
count: int = 1,
parcel_id str | bool = False,
offset: int = 0,
):
stmt = select(Land).offset(offset).limit(count)
if longitude is not False:
stmt.where(Land.longitude.is_(longitude))
if latitude is not False:
stmt.where(Land.latitude.is_(latitude))
if entity is not False:
stmt.where(Land.address.is_(address))
if county is not False:
stmt.where(Land.county.is_(county))
if parcel_id is not False:
stmt.where(Land.parcel_id.is_(parcel_id))
records = session.execute(stmt).all()
entries = []
for object in records:
entries.append((object[0].to_dict()))
return entries