George Vas
George Vas

Reputation: 125

Python Django group by date

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.

Upvotes: 0

Views: 908

Answers (2)

TaipanRex
TaipanRex

Reputation: 820

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.

Upvotes: 2

kender99
kender99

Reputation: 323

You could do something like

select date(starttime) as simple_date
from your_table
group by simple_date

Upvotes: 0

Related Questions