2024-07-12 02:30:17 +02:00
|
|
|
from typing import TypeVar
|
2023-12-15 21:10:20 +01:00
|
|
|
|
|
|
|
from django.db import models
|
2024-08-25 02:30:41 +02:00
|
|
|
from django.db.models import QuerySet
|
2023-12-15 21:10:20 +01:00
|
|
|
|
|
|
|
ModelT = TypeVar("ModelT", bound=models.Model)
|
|
|
|
RowT = TypeVar("RowT")
|
|
|
|
|
|
|
|
|
|
|
|
def query_for_ids(
|
2024-08-25 02:30:41 +02:00
|
|
|
query: QuerySet[ModelT, RowT],
|
2024-07-12 02:30:17 +02:00
|
|
|
user_ids: list[int],
|
2023-12-15 21:10:20 +01:00
|
|
|
field: str,
|
2024-08-25 02:30:41 +02:00
|
|
|
) -> QuerySet[ModelT, RowT]:
|
2023-12-15 21:10:20 +01:00
|
|
|
"""
|
|
|
|
This function optimizes searches of the form
|
|
|
|
`user_profile_id in (1, 2, 3, 4)` by quickly
|
|
|
|
building the where clauses. Profiling shows significant
|
|
|
|
speedups over the normal Django-based approach.
|
|
|
|
|
|
|
|
Use this very carefully! Also, the caller should
|
|
|
|
guard against empty lists of user_ids.
|
|
|
|
"""
|
|
|
|
assert user_ids
|
|
|
|
clause = f"{field} IN %s"
|
2024-06-27 20:17:17 +02:00
|
|
|
query = query.extra( # noqa: S610
|
2023-12-15 21:10:20 +01:00
|
|
|
where=[clause],
|
|
|
|
params=(tuple(user_ids),),
|
|
|
|
)
|
|
|
|
return query
|