Optimizing search with multiple linked rows

You really should be allowing the database to filter, not doing so in a list comprehension. Avoid fetching everything and filtering yourself unless you absolutely cannot do the filtering using db features.

In your case, you can filter based on the linked field by looking up the linked rows, e.g. (untested code warning):

locations = app_tables.location.search(country=filter_tuple[0])
customers = app_tables.customer.search(status=filter_tuple[1], location=q.any_of(*locations))

Refer to the query operators blog post for more details on q.any_of: Querying Data Tables

4 Likes