Hello everyone !
I am trying to filter a subquery and Slice it by the value of an annotated field.
Solution 1: Failed
Subquery(
MyModel.objects.all()[:OuterRef(‘custom_index’)]
)
As Django ORM doesn’t support this way,
–
Solution 2:
I thought of using RowNumber and filter against it like:
Subquery(
MyModel.objects
.annotate(
row_nb=Window(
expression=RowNumber(),
order_by=F(‘sale_datetime’).asc(),
)
)
.filter(
row_nb__lte=F(‘custom_index’)
)
)
But it is not supported (yet?)
–
Solution 3: Failed
Then I thought of creating an ArrayAgg of the ‘sale_datetime’ and try to extract the nth index with a custom Expression such as:
annotate_array=ArrayAgg(‘content__sale_datetime’)
annotate_val=ArrayIndex(‘annotate_array’, F(‘custom_index’))
class ArrayIndex(Func):
function = ‘ARRAY’
template = “%(function)s[%(expressions)s]”def __init__(self, expression, index, **extra): output_field = extra.pop('output_field', None) super().__init__(expression, index, output_field=output_field, **extra)
But it’s raising some django.db.utils.ProgrammingError and I’m not proficient enough make it operate, nor can find enough documentation and examples on the matter…
–
Solution 4: Last and less efficient way
Populate a “row_nb” when creating / updating the items one by one and filter against it.
–
If anyone already had the same issue or has an alternative to handle this queryset “on the fly”, don’t hesitate to comment !
Thank you for your time guies.