If I have a list of (sometimes) repeating ids and I want to query a table based on this list, is there a better way to do it, other than the following example:
def get_sensors_by_ids(self, ids: List[int]) -> List[SensorModel]:
query = (
"SELECT * FROM sensor "
"WHERE id = %s"
)
sensor_models = []
with self.connection.cursor(dictionary=True, buffered=True) as cursor:
for id in ids:
cursor.execute(query, (id,))
result = cursor.fetchone()
sensor_models.append(
SensorDatabaseModel.parse_obj(result).to_sensor_model()
)
return sensor_models
In the case above I want to return exactly one SensorModel
instance per given ids
item.
ids
could have the same value for every item, sometimes repeating values or all unique values, eg
ids = [1, 1, 1, 1, 1, 1, 1, 1, ... ]
ids = [1, 1, 1, 1, 2, 2, 2, 2, ... ]
ids = [1, 2, 3, 4, 5, 6, 7, 8, ... ]
ids = [1, 22, 313, 4, 65, 16, 347, 228, ... ]
The code above works and I don't expect huge amount of data in the tables, but I still don't like the solution above where all is done in separate queries.