Hi! Can you show me example usage of this method with example output?
Python
def get_data_w_like_2(
session: Session,
table: Any,
sort_columns: Optional[List[Any]] = None,
sort_orders: Optional[List[str]] = None,
datetime_column: Optional[Any] = None,
datetime_switch: bool = False,
**filters
) -> List[Any]:
query = session.query(table)
filter_conditions = []
# Handle datetime_switch condition
if datetime_switch and datetime_column is not None:
filter_conditions.append(datetime_column.is_(None))
# Process filters
special_ops = {}
regular_filters = {}
# First, separate special operations from regular filters
for key, value in filters.items():
if isinstance(key, str) and key.endswith('_op'):
special_ops[key] = value
else:
regular_filters[key] = value
# Process special operations
for key, op in special_ops.items():
column_name = key[:-3]
if column_name not in regular_filters:
continue
column = getattr(table, column_name, None)
if not column:
raise ValueError(f"Invalid column name: {column_name}")
value = regular_filters.pop(column_name) # Remove from regular filters
if op == '>':
filter_conditions.append(column > value)
elif op == '<':
filter_conditions.append(column < value)
elif op == '!=':
filter_conditions.append(column != value)
elif op == 'like':
filter_conditions.append(column.like(value))
else:
raise ValueError(f"Unsupported operation: {op}")
# Process remaining regular filters
for key, value in regular_filters.items():
column = getattr(table, key, None)
if not column:
raise ValueError(f"Invalid column name: {key}")
filter_conditions.append(column == value)
# Apply filters
if filter_conditions:
query = query.filter(and_(*filter_conditions))
# Apply sorting
if sort_columns:
ordering = []
if sort_orders:
if len(sort_columns) < len(sort_orders):
sort_orders = sort_orders[:len(sort_columns)]
for col, order in zip_longest(sort_columns, sort_orders, fillvalue='asc'):
if order.lower() == 'asc':
ordering.append(asc(col))
elif order.lower() == 'desc':
ordering.append(desc(col))
else:
raise ValueError("sort_orders must be 'asc' or 'desc'.")
else:
ordering = [asc(col) for col in sort_columns]
query = query.order_by(*ordering)
# Print the SQL query for debugging
# print(query)
return query.all()
Assistant
Here's an example usage of the get_data_w_like_2 method with sample outputs:
python
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
# Define model
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
created_at = Column(DateTime)
# Setup test database
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# Add test data
users = [
User(name='John Doe', age=35, created_at=datetime(2020, 1, 1)),
User(name='Jane Smith', age=28, created_at=datetime(2021, 2, 2)),
User(name='John Wick', age=40, created_at=None),
User(name='Alice', age=30, created_at=datetime(2022, 3, 3))
]
session.add_all(users)
session.commit()
# Example 1: Filter name like 'John%', age > 30, sort by age descending
result = get_data_w_like_2(
session=session,
table=User,
sort_columns=[User.age],
sort_orders=['desc'],
name='John%',
name_op='like',
age=30,
age_op='>'
)
print([(u.name, u.age) for u in result])
# Output: [('John Wick', 40), ('John Doe', 35)]
# Example 2: Find users with NULL created_at
result = get_data_w_like_2(
session=session,
table=User,
datetime_column=User.created_at,
datetime_switch=True
)
print([(u.name, u.created_at) for u in result])
# Output: [('John Wick', None)]
# Example 3: Exact name match with sorting
result = get_data_w_like_2(
session=session,
table=User,
sort_columns=[User.name],
name='Jane Smith'
)
print([(u.name, u.age) for u in result])
# Output: [('Jane Smith', 28)]
Key features demonstrated:
Special operators using _op suffix (like name_op='like')
DateTime NULL filtering with datetime_switch
Regular equality filters (no _op suffix)
Sorting combinations with sort_columns and sort_orders
The outputs reflect the sample data filtered and sorted according to the parameters passed.
User
Is there a way to make such query, that i would get all workers from my DB if flag is setted to some special value or only workers, that have their target_id equals to some integer?
Python
def testing(flag=None):
query = get_data_w_like_2(
session=session,
table=guts.TargetWorkers,
sort_columns=[guts.TargetWorkers.worker_id],
sort_orders=['asc'],
target_id=flag,
)
print(len(query))
for row in query:
print(f'{row.worker_id}: {row.target_id}')
Assistant
To achieve the desired behavior where the query returns all workers if the flag is a special value (e.g., None) or filters by target_id otherwise, modify the testing function to conditionally include the target_id filter:
python
def testing(flag=None):
# Conditionally add target_id filter only if flag is not the special value
filters = {}
if flag is not None: # Assuming special value is None
filters['target_id'] = flag
query = get_data_w_like_2(
session=session,
table=guts.TargetWorkers,
sort_columns=[guts.TargetWorkers.worker_id],
sort_orders=['asc'],
**filters # Pass filters dynamically
)
print(len(query))
for row in query:
print(f'{row.worker_id}: {row.target_id}')
Explanation:
Conditional Filter Logic:
If flag is the special value (e.g., None), filters remains empty, so no target_id filter is applied.
If flag is a valid integer, filters['target_id'] = flag adds the filter condition.
Dynamic Filter Application:
The **filters syntax passes the key-value pairs (like target_id=flag) to get_data_w_like_2, which applies them as target_id == flag.
Example Outcomes:
When flag=None: All workers are returned (no target_id filter).
When flag=5: Only workers with target_id=5 are returned.
User
Is there a way to make such query, that i would get all workers from my DB if flag is setted to some special value or only workers, that have their target_id equals to some integer?
Python
def testing(flag=None):
query = get_data_w_like_2(
session=session,
table=guts.TargetWorkers,
sort_columns=[guts.TargetWorkers.worker_id],
sort_orders=['asc'],
target_id=flag,
)
print(len(query))
for row in query:
print(f'{row.worker_id}: {row.target_id}')
Assistant
To achieve this, modify the testing function to conditionally include the target_id filter based on the flag value:
python
def testing(flag=None):
# Only add target_id filter if flag is not the special value
params = {
'session': session,
'table': guts.TargetWorkers,
'sort_columns': [guts.TargetWorkers.worker_id],
'sort_orders': ['asc']
}
# Add target_id filter only when flag is not None (or your special value)
if flag is not None:
params['target_id'] = flag
query = get_data_w_like_2(**params)
print(len(query))
for row in query:
print(f'{row.worker_id}: {row.target_id}')
Key Changes:
Conditional Filter: The target_id parameter is only added to the query when flag is not the special value (assumed to be None in this example)
Default Behavior: When flag=None, no target_id filter is applied, returning all workers
Filtered Behavior: When flag is set to a value (e.g., testing(5)), it returns workers where target_id=5
This maintains the existing sorting while adding dynamic filtering based on the flag value.
User
Is there a way to pass multiple values to a single column not in a loop, but with something like an Or operator? For example, if i want to get information about multiple workers.
Assistant
Yes, you can achieve this by modifying the get_data_w_like_2 function to support an in operator. Here's how:
1. Update the get_data_w_like_2 function to handle in operator:
Add this condition in the special operations processing section:
python
# Add to the elif chain in special_ops processing
elif op == 'in':
filter_conditions.append(column.in_(value))
2. Use it in your query like this:
python
def testing(flag=None):
filters = {'target_id': flag}
# Add operator if flag is a list/tuple
if isinstance(flag, (list, tuple)):
filters['target_id_op'] = 'in'
query = get_data_w_like_2(
session=session,
table=guts.TargetWorkers,
sort_columns=[guts.TargetWorkers.worker_id],
sort_orders=['asc'],
**filters
)
print(len(query))
for row in query:
print(f'{row.worker_id}: {row.target_id}')
Key changes:
Operator Support: Added elif op == 'in' to handle list-based filtering
Dynamic Operator: Checks if flag is a list/tuple and adds target_id_op='in'
Example usage:
python
# Get workers where target_id is 1, 3, or 5
testing([1, 3, 5])
# Get all workers (flag=None)
testing()
This approach allows you to pass multiple values in a list and get SQL IN clause behavior without loops.