MikeVelazco
MikeVelazco

Reputation: 905

How can I make a query with contains over date/datetime fields

Im trying to use the datatables jQuery plugin with date/datetime fields. and when you make the query that contains those field generates a MySQL Warning when you try to use __contains in the queryset. I've detected that if you try to make queries over Year, Month and Day the warning doesn't appears.

There's another way to search in a date/datetime field without raise that warning or how could I make a query over a year/month/day in a date/datetime field.

Here is an example:

Model.objects.filter(Date__contains="2014")

Which gives this warning:

Warning: Incorrect date value: '%2014%' for column 'Fecha' at row 1

I'd like to make a query like this:

SELECT * FROM Model WHERE YEAR(Date) LIKE "%4%" OR MONTH(Date) LIKE "%4%" OR DAY(Date) LIKE "%4%";

Upvotes: 3

Views: 1437

Answers (2)

MikeVelazco
MikeVelazco

Reputation: 905

The best solution that I´ve found is searching by a Regex

Model.objects.filter(Date__regex="4")

Upvotes: 2

Pradeep Agnihotri
Pradeep Agnihotri

Reputation: 371

Model.objects.filter(field_name__year=2014)

Upvotes: 0

Related Questions