Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter by hour

Tags:

python

django

I've found that link: http://code.djangoproject.com/attachment/ticket/8424/time_filters.diff and changed 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)

like image 386
DJPy Avatar asked Jun 06 '10 15:06

DJPy


2 Answers

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).

like image 160
zovision Avatar answered Oct 07 '22 11:10

zovision


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.

like image 31
akaariai Avatar answered Oct 07 '22 10:10

akaariai