Django filter by hour
I've found that link: http://code.djangoproject.com/attachment/ticket/8424/time_filters.diff and chang开发者_运维问答ed my django 1.2 files by adding taht what you can see there.
But now, when I'm trying to write Entry.objects.filter(pub_date__hour = x) - the result is following error:Field has invalid lookup: hour
What should I do else, to make it work?
(sorry for my english)
Entry.objects.filter(pub_date__hour = x)
is not supported as of django 1.2 - only year, month, day, week_day.
Use something like this:
Entry.objects.filter(pub_date__regex = '08:00')
or
Entry.objects.filter(pub_date__contains = '08:00')
which will give you all Entry objects with the hour (over all years).
This is supported natively by Django, using the hour
field lookup:
Event.objects.filter(timestamp__hour=23)
Event.objects.filter(time__hour=5)
Event.objects.filter(timestamp__hour__gte=12)
This is equivalent to using SQL EXTRACT('hour' FROM timestamp)
.
When USE_TZ
is True, datetime fields are converted to the current time zone before filtering.
Django 1.7 added support for custom lookups and transforms. A hour transform is implemented as follows on PostgreSQL:
class HourExtract(models.Transform):
lookup_name = 'hour'
output_type = models.IntegerField()
def as_sql(self, compiler, connection):
lhs_sql, lhs_params = compiler.compile(self.lhs)
return "EXTRACT(hour FROM %s)" % lhs_sql, lhs_params
models.DateTimeField.register_lookup(HourExtract)
Now you can do .filter(pub_date__hour__lte=x) and other similar queries on the hour value.
Probably better of using a raw SQL query like:
Whatever.objects.raw("SELECT * FROM table WHERE TIME(pub_date) LIKE '%%08:30%%' ")
Maybe you defined pub_date
as a DateField
, but it must be a DateTimeField
? Can you include in the question your model definition code?
精彩评论