python 38 lines · 1 tab

Django ORM window functions for analytics

Priya Sharma Jan 2026
1 tab
from django.db.models import F, Window
from django.db.models.functions import RowNumber, Rank, DenseRank
from products.models import Sale


def get_sales_with_ranking():
    """Add rank to sales by amount."""
    sales = Sale.objects.annotate(
        rank=Window(
            expression=Rank(),
            order_by=F('amount').desc()
        ),
        row_number=Window(
            expression=RowNumber(),
            order_by=F('created_at').desc()
        )
    )
    return sales


def get_salesperson_rankings():
    """Rank salespeople within each region."""
    from django.db.models import Sum

    sales = Sale.objects.values(
        'salesperson__name',
        'salesperson__region'
    ).annotate(
        total_sales=Sum('amount')
    ).annotate(
        region_rank=Window(
            expression=Rank(),
            partition_by=[F('salesperson__region')],
            order_by=F('total_sales').desc()
        )
    ).order_by('salesperson__region', 'region_rank')

    return sales
1 file · python Explain with highlit

Window functions perform calculations across rows related to the current row. I use them for running totals, rankings, and moving averages. Django's Window expression with functions like RowNumber, Rank, DenseRank provide SQL window function support. This is more efficient than Python-side calculations. I partition data with partition_by and order with order_by. Window functions are perfect for leaderboards, time-series analysis, and comparative metrics. They require PostgreSQL or other databases supporting window functions.


Related snips

python
import os
import stat

for root, _dirs, files in os.walk('/etc'):
    for name in files:
        path = os.path.join(root, name)

Python security audit script for exposed risky filesystem state

python auditing host-security
by Kai Nakamura 1 tab
python
class Product(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    cost = models.DecimalField(max_digits=10, decimal_places=2)
    margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)

Django model signals vs overriding save

django python models
by Priya Sharma 2 tabs
python
from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [

Django URL namespacing and reverse lookups

django python urls
by Priya Sharma 3 tabs
ruby
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]

sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first

SQL injection prevention with unsafe and safe query patterns

sql-injection owasp database
by Kai Nakamura 3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment


class PostType(DjangoObjectType):

Django GraphQL with Graphene

django python graphql
by Priya Sharma 2 tabs
sql
-- EXPLAIN ANALYZE (actual execution statistics)
EXPLAIN ANALYZE
SELECT u.username, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at >= '2024-01-01'

Advanced query optimization techniques

database optimization query-performance
by Maria Garcia 2 tabs

Share this code

Here's the card — post it anywhere.

Django ORM window functions for analytics — share card
Link copied