Skip to content

Instantly share code, notes, and snippets.

@cchurch
Created November 26, 2013 03:42
Show Gist options
  • Save cchurch/7653156 to your computer and use it in GitHub Desktop.
Save cchurch/7653156 to your computer and use it in GitHub Desktop.
Custom Django aggregate function for replacing average value of NULL with 0.
import django.db.models.sql.aggregates
import django.db.models.aggregates
class AvgWithZeroForNull(django.db.models.sql.aggregates.Avg):
sql_template = 'COALESCE(%(function)s(%(field)s), 0)'
django.db.models.sql.aggregates.AvgWithZeroForNull = AvgWithZeroForNull
class AvgWithZeroForNull(django.db.models.aggregates.Avg):
name = 'AvgWithZeroForNull'
django.db.models.aggregates.AvgWithZeroForNull = AvgWithZeroForNull
# Usage (to retrieve objects with highest average, NULLs become zeroes and are last):
# MyModel.objects.annotate(average=AvgWithZeroForNull('other_model__field_name')).order_by('-average')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment