0

I'm building a web app using Django. One of my models is this:

class Change(models.Model):
   user=models.ForeignKey(User)
   project=models.ForeignKey('Project')
   starttime=models.DateTimeField(null=True,blank=True)
   endtime=models.DateTimeField(null=True, blank=True)
   worktime=models.FloatField(null=True, blank=True)#worktime is in hours
   comment=models.CharField(max_length=500)
   flagged=models.BooleanField(default=False, db_index=True)

As you can see the starttime and endtime are datetime objects. I want to run a sql query grouping the results by date. But since the objects are datetime, they are grouped by date and time. Is it possible? I looked at both Python and Django docs without find anything useful. Thank you.

Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
George Vas
  • 113
  • 2
  • 11
  • 1
    Take a look at [Annotate (group) dates by month/year in Django](http://stackoverflow.com/questions/21837227/annotate-group-dates-by-month-year-in-django) and [Django group by dates and SUM values](http://stackoverflow.com/questions/18099697/django-group-by-dates-and-sum-values) – Mauro Baraldi May 13 '15 at 15:13
  • Possible duplicate of [Django: Group by date (day, month, year)](http://stackoverflow.com/questions/8746014/django-group-by-date-day-month-year) – tback Jun 24 '16 at 07:28

2 Answers2

2

You could use datetime.datetime.date('starttime') to get the date from the DateTimeField. Then take a look at the Django docs on aggregation for grouping.

TaipanRex
  • 795
  • 5
  • 11
0

You could do something like

select date(starttime) as simple_date
from your_table
group by simple_date
kender99
  • 213
  • 2
  • 7
  • 3
    What does this have to do with Python or Django? While this expresses a solution in raw SQL, it doesn't show how to use that in either Django or Python, so strictly speaking it doesn't answer the question – dKen Dec 07 '16 at 18:10