Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom transform for django date filter. It works like charm. :)
from django.db import models
from django.db.models import Transform
# Custom Date filter transform class
# Added by : Jay Modi
class MySQLDatetimeDate(Transform):
"""
This implements a custom SQL lookup when using `__date` with datetimes.
To enable filtering on datetimes that fall on a given date, import
this transform and register it with the DateTimeField.
http://blog.zdsmith.com/comparing-dates-and-datetimes-in-the-django-orm.html
"""
lookup_name = 'customdate'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'DATE({})'.format(lhs), params
@property
def output_field(self):
return models.DateField()
# https://docs.djangoproject.com/en/1.8/howto/custom-lookups/#a-simple-transformer-example
# Added by : Jay Modi
from django.db.models import DateField
DateField.register_lookup(MySQLDatetimeDate)
dt = datetime.strptime(year+"/"+month+"/"+day, "%Y/%m/%d").date()
modelobj.objects.filter(date__customdate = dt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment