Last active
August 19, 2019 08:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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