Skip to main content

Django Nested Query

Project description

django-nestedquery

Given a django model such as

class SensorReading(models.Model):
    sensor=models.PositiveIntegerField()
    timestamp=models.DatetimeField()
    reading=models.IntegerField()

This allows the construction of queries such as

from nestedquery import NestedQuery

qs=NestedQuery(SensorReading.objects.filter(sensor=1)).filter(reading__gte=10)

resulting in SQL looking something like

SELECT * FROM (
    SELECT * FROM SensorReading
    WHERE sensor = 1
) as VirtualTable
WHERE VirtualTable.reading >= 10;

While this example is obviously simplistic, This Pattern becomes more useful when dealing with more complex queries, for example when dealing with aggregates

readings = (
    NestedQuery(
        SensorReading.objects.filter(**filters)
        .annotate(
            previous_read=Window(
                expression=window.Lead("timestamp"),
                partition_by=[F("sensor"),],
                order_by=[
                    "timestamp",
                ],
                frame=RowRange(start=-1, end=0),
            )
        )
        .annotate(delta=Abs(Extract(F("timestamp") - F("previous_read"), "epoch")))
    )
    .values("sensor")
    .annotate(min=Min("delta"), max=Max("delta"))
)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-nestedquery-0.1.0.tar.gz (2.3 kB view hashes)

Uploaded Source

Built Distribution

django_nestedquery-0.1.0-py3-none-any.whl (2.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page