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.2.0.tar.gz (2.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_nestedquery-0.2.0-py3-none-any.whl (2.7 kB view details)

Uploaded Python 3

File details

Details for the file django-nestedquery-0.2.0.tar.gz.

File metadata

  • Download URL: django-nestedquery-0.2.0.tar.gz
  • Upload date:
  • Size: 2.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.11.1

File hashes

Hashes for django-nestedquery-0.2.0.tar.gz
Algorithm Hash digest
SHA256 242edbdac16e173d880e0f8c67db89577cace40924d2bb3f10445fa0086498a8
MD5 8f594cab95f89f4119c9db8f702a7b72
BLAKE2b-256 1118b3e6d00dc206147ef34cff304a1a887fae4eb329e45cc5a2c9dd3c20c88e

See more details on using hashes here.

File details

Details for the file django_nestedquery-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_nestedquery-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 db7379d8c877eb467569b979c061642d30dd909113a62f0c9d9aa1f00db95de1
MD5 1881159a8f1a92a93718d0eefa68ac27
BLAKE2b-256 51ae7c40a98b13525d911a4f4f65b2d67b4ea43dc564522a1da8e00ff2dfc6ba

See more details on using hashes here.

Supported by

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