Using Flask SQLAlchemy I'm querying a MySQL database with a table called bar
and looking for rows that match a filter consisting of foo
and country_code
:
foo_filter = 'hello'
country_code_filter = 'ES'
result = Bar.filter_by(foo=foo_filter, country_code=country_code_filter).first()
The above code will return the first row in which foo = foo_filter
and country_code = country_code_filter
.
However, it's possible that we might not have rows for certain country codes that match foo
. In these cases (i.e, cases where the above query returns 0 results), I'd like to use a default country filter of 'RoW' as our dataset should always have an RoW value for each possible value of foo
. In the unexpected occurrence that this also doesn't return any results then an error should be thrown. This is the code I have for this:
foo_filter = 'hello'
country_code_filter = 'ES'
result = Bar.filter_by(foo=foo_filter, country_code=country_code_filter).first()
if not result:
result = Bar.filter_by(foo=foo_filter, country_code='RoW').first()
if not result:
raise RuntimeException(f"No data for combination {foo_filter}, {country_code_filter} or {foo_filter}, RoW")
This approach of running similar queries multiple times and checking the result each time until I get a row feels very messy/wrong but I haven't been able to find any better approaches that allow you to set an 'alternative' filter when your initial query returns 0 rows in Flask SQLAlchemy
Is there a cleaner approach to this?