A
A
Anton2021-02-05 17:52:56
Django
Anton, 2021-02-05 17:52:56

How to filter the result of a window function in Django?

I annotate the selection with row numbers using a window function. I want the line number to remain the same after filtering.
In this case, filtering occurs before the window function is applied:

from django.db.models import F, Window
from django.db.models.functions import RowNumber

queryset.annotate(
    num=Window(RowNumber(), order_by=F('field').asc()),
).filter(name__startswith='A')

There is a ticket for this, which is also referenced in the comments to the old question .

Thought to break the actions:
ids_nums = queryset.annotate(
    num=Window(RowNumber(), order_by=F('field').asc()),
).values('id', 'num')
queryset.filter(name__startswith='A').annotate(num=???)

But here it is not clear how to connect the filtered rows by id with ids_nums and annotate with num values.

Is it still possible to implement such work without third-party libraries?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question