Skip to content

Instantly share code, notes, and snippets.

@vdboor
Last active August 19, 2019 08:22
Show Gist options
  • Save vdboor/f3ebe5e20c0882d39053 to your computer and use it in GitHub Desktop.
Save vdboor/f3ebe5e20c0882d39053 to your computer and use it in GitHub Desktop.
Allow to use DATE_TRUNC('month', "date_field") in PostgreSQL for Django 1.8+. I'm using this for django-oscar reports per month/week/year.
from django.db.models import Func, Value
class DateTrunc(Func):
"""
To support using DATE_TRUNC('text', "field") in SQL
Example::
order_totals = (orders
.annotate(
period=DateTrunc('month', 'date_placed'),
)
.values("period") # Needs to be in between for a correct GROUP_BY
.order_by('period')
.annotate(
order_count=Count('id'),
shipping_excl_tax=Sum('shipping_excl_tax'),
shipping_incl_tax=Sum('shipping_incl_tax'),
))
"""
function = 'DATE_TRUNC'
def __init__(self, trunc_type, field_expression, **extra):
super(DateTrunc, self).__init__(Value(trunc_type), field_expression, **extra)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment