views:

843

answers:

2

What is the optimal query to obtain all the records for one specific day? In my Weather model, 'timestamp' is a standard DateTimeField.

I'm currently using

start = datetime.datetime(2009, 1, 31)
end = start + datetime.timedelta(hours=23, minutes=59, seconds=59)
Weather.objects.filter(timestamp__range=(start, end))

but wonder if there is a more efficient method.

+1  A: 
  1. Do not prematurely optimize
  2. Index columns that your queries are based on frequently
  3. Optimize expensive columns, like add auto-updated year, month, and day values (maybe just as a string) if and only if tests show it provides a significant speedup and only after using what already works NOW and determining it isn't viable.
ironfroggy
+3  A: 

The way it's done in django.views.generic.date_based is:

{'date_field__range': (datetime.datetime.combine(date, datetime.time.min),
                       datetime.datetime.combine(date, datetime.time.max))}

There should soon be a patch merged into Django that will provide a __date lookup for exactly this type of query (http://code.djangoproject.com/ticket/9596).