Skip to content

Instantly share code, notes, and snippets.

@jourdanrodrigues
Created December 20, 2024 16:26
Show Gist options
  • Save jourdanrodrigues/49cc4bd6efe6f1fb46b31c3b3380ce1f to your computer and use it in GitHub Desktop.
Save jourdanrodrigues/49cc4bd6efe6f1fb46b31c3b3380ce1f to your computer and use it in GitHub Desktop.
from django_cte.raw import raw_cte_sql
from django_cte import CTEQuerySet, With
class CustomQuerySet(CTEQuerySet):
def filter_by_uuids(self, uuids: Sequence):
valid_uuids = [value for value in uuids if is_valid_uuid(value)]
placeholders = ",".join(["%s"] * len(valid_uuids))
uuid_table = With(
raw_cte_sql(
f"SELECT uuid_field FROM UNNEST(ARRAY[{placeholders}]::uuid[]) AS uuid_field",
valid_uuids,
{"uuid_field": models.UUIDField()},
),
name="uuids_table",
)
return uuid_table.join(
self, uuid=uuid_table.col.uuid_field, _join_type=INNER
).with_cte(uuid_table)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment