I am using DataTables for my front end and it allows a global search (iterating through all the fields to find matches).
This is what I want to be able to do in django (version 1.9.1):
- use “ma” as a filter for a DateField so that all March and May dates are returned
or
- use “Mar 1” as a filter for a DateField so that all dates between March 10 – March 19 are returned
After some tinkering, I have this custom lookup
from django.db.models import Lookup
from django.db.models.fields import DateField
@DateField.register_lookup
class DateTextFilter(Lookup):
lookup_name = 'dttxt'
def as_postgresql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs = self.rhs.strftime("%b %d, %Y")
return "to_char(%s,'Mon DD, YYYY') ~* '%s'", ([lhs,rhs])
which I run like this:
outputQ = Q(**{"appt_date"+"__dttxt" : "Mar 09"})
Appts.objects.filter(outputQ)
It produces SQL that runs (in Postgres) but when I run filter(), I get the error
ValidationError: [u"'Mar 09' value has an invalid date format.
It must be in YYYY-MM-DD format."]
Fair enough, “Mar 09” is not a valid date – but the raw SQL is valid and runs ( I tested this with '2016-03-09' to bypass this error and get django to create the SQL)
SELECT "appts"."appt_id", "appts"."client_id", "appts"."therapist_id",
"appts"."agency_id", "appts"."appt_date", "appts"."appt_start",
"appts"."appt_end", "appts"."cpt_code", "appts"."client_owe",
"appts"."insur1_owe", "appts"."insur2_owe", "appts"."note",
"appts"."note_flag", "appts"."ct_fee_pd", "appts"."subm_date",
"appts"."updated" FROM "appts" WHERE to_char("appts"."appt_date",'Mon DD,
YYYY') ~* 'Mar 09'
I could use extra() but this will be deprecated.
I am probably going to wind up parsing the string using this SO algorithm (using raw sql is too large of a compromise just to gain this functionality), but I will lose some of the functionality that I want .
Not sure if this is doable...