Django Filter by Clock

I found this link: http://code.djangoproject.com/attachment/ticket/8424/time_filters.diff and changed the django 1.2 files by adding taht, which you can see there. But now, when I try to write Entry.objects.filter (pub_date__hour = x), the result is the following error:

The field has an invalid search: hour

What should I do next for it to work?

(sorry for my English)

+5
source share
4 answers
Entry.objects.filter(pub_date__hour = x)

not supported in 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 a clock (for all years).

+4
source

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

.filter(pub_date__hour__lte = x) .

+2

It is probably best to use a raw SQL query, for example:

Whatever.objects.raw("SELECT * FROM table WHERE TIME(pub_date) LIKE '%%08:30%%' ")
+1
source

Maybe you determined pub_datehow DateField, but it should be DateTimeField? Can you include your model definition code in the question?

0
source

All Articles