Home > Back-end >  Date Format in Django views complex sql
Date Format in Django views complex sql

Time:08-02

I need create select to database where I have rows with date in this format:

2020-08-21 10:43:26.000000

And I need change this date like as this:

Month-Day (Jan-02 for example)

And after that this column group by... I am try many things what I found here but nothing works... :/

Right now my query looks like this:

hist_data = Vpnhistory.objects.filter(bytes_sent__gt=0)
    hist_data = hist_data.filter(end_time__gte=datetime.now()-timedelta(days=14))
    hist_data = hist_data.values('end_time', 'bytes_sent')
    hist_data = hist_data.annotate(summ=Sum('bytes_sent'), end_time_str=DateToChar(F('end_time'), Value('MM-DD')))

And class DateToChar like this in my models.py:

class DateToChar(models.Func):
    arity = 2
    function = 'to_char'
    output_field = models.CharField()

Datum still returns with full datetime format .. :/

CodePudding user response:

Django already has some logic to do this without converting this to a string. You can work with TruncDate [Django-doc], and then thus process this with:

from django.db.models import Sum
from django.db.models.functions import TruncDate, Now

hist_data = Vpnhistory.objects.filter(
    bytes_sent__gt=0, end_time__gte=Now()-timedelta(days=14)
).values(date=TruncDate('end_time')).annotate(
    summ=Sum('bytes_sent')
).order_by('date')
  • Related