python / expert
Snippet
Eigene SQL-Aggregate mit bedingten FILTER-Klauseln im Django ORM
Benutzerdefinierte SQL-Aggregate erweitern den Django-ORM-Funktionsumfang. Das Erstellen einer Unterklasse von `Aggregate` mit eigenem Template ermöglicht die Übersetzung von PostgreSQL-nativen `FILTER (WHERE ...)`-Klauseln direkt in SQL.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.db.models import Aggregate, FloatFieldclass FilteredAvg(Aggregate):function = 'AVG'template = '%(function)s(%(expressions)s) FILTER (WHERE %(condition)s)'output_field = FloatField()def __init__(self, expression, condition, **extra):super().__init__(expression, condition=condition, **extra)# Usage Example:# Article.objects.aggregate(# avg_high_rating=FilteredAvg('rating', condition="rating >= 4.0")# )
django
Erklärung
1
class FilteredAvg(Aggregate):
Erstellt eine Unterklasse der Django-Aggregate-Basisklasse zur Einbindung bedingter SQL-Aggregationen.
2
template = '%(function)s(%(expressions)s) FILTER (WHERE %(condition)s)'
Definiert die Roh-SQL-Vorlage unter Verwendung der PostgreSQL FILTER-Syntax für bedingte Aggregationen.
3
super().__init__(expression, condition=condition, **extra)
Übergibt den Zielausdruck sowie die Filterbedingung an den Django ORM Query-Compiler.