Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering on a Window function in Django

I have the following model:

class Foobar(models.Model):
    foo = models.IntegerField()

And I figured out how to calculate the delta of consecutive foo fields by using window functions:

qs = Foobar.objects.annotate(
    delta=F('foo') - Window(
        Lag('foo'),
        partition_by=F('variant'),
        order_by=F('timestamp').asc(),
    )
)

Now I only want the records from this where delta is negative:

qs.filter(delta__lte=0)

But as you might expect, this gives an error:

django.db.utils.NotSupportedError: Window is disallowed in the filter clause.

How can I do this filtering with the Django ORM?

like image 219
Code-Apprentice Avatar asked Apr 27 '26 02:04

Code-Apprentice


1 Answers

Django 4.2 supports filtering on WINDOW expressions. See the release notes and also the pull request.

like image 191
jnns Avatar answered Apr 29 '26 16:04

jnns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!